jsp 中文件上传
以下是代码:String fileName = " "; String appPath = request.getSession().getServletContext().getRealPath("/") ; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(cacheSize); //缓冲大小 File temFile = new File(appPath+tempFileFold); //超过缓冲小放在临时文件夹,再一步一步上传 if(!temFile.exists()){ temFile.mkdirs(); } factory.setRepository(temFile); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileSize); //最大大小 List fileList = null ; try { fileList = upload.parseRequest(request); } catch (FileUploadException e) { if (e instanceof SizeLimitExceededException) { System.out.println("超过大小了,返回!"); double maxSize = maxFileSize/(1024.0*1024.0); if(maxSize>1.0){ float fileSize = Math.round(maxSize*1000)/1000; request.setAttribute("message", MessageResource.readByString("file_size_overflow")+fileSize+"M"); }else{ double kMaxSize = maxFileSize/(1024.0); float fileSize = Math.round(kMaxSize*100)/100; request.setAttribute("message", MessageResource.readByString("file_size_overflow")+fileSize+"K"); } request.setAttribute("page", request.getParameter("failpage")); System.out.println("page:"+request.getAttribute("page")+" messgae:"+request.getAttribute("message")); return ""; } e.printStackTrace(); } if (fileList == null || fileList.size() == 0) { System.out.println("空文件,返回!"); return ""; } // 得到所有上传的文件 Iterator fileItr = fileList.iterator(); // 循环处理所有文件 while (fileItr.hasNext()) { FileItem fileItem = null; String path = null; long size = 0; // 得到当前文件 fileItem = (FileItem) fileItr.next(); // 忽略简单form字段而不是上传域的文件域(等) if (fileItem == null || fileItem.isFormField()) { continue; } // 得到文件的完整路径 path = fileItem.getName(); // 得到文件的大小 size = fileItem.getSize(); if ("".equals(path) || size == 0) { System.out.println("空文件2,返回!"); return "" ; }
jsp上传了xls文件。
Servlet这边怎么接收?详情看下面代码
获取文件,需要用到上传/下载组件,比如用SmartUpload,获取页面上传的excel.xls文件:SmartUpload su = new SmartUpload();//新建一个SmartUpload对象su.getRequest().getParameterValues();取数组值,因为文件流都是2进制,然后再用文件流写成文件即可。
jsp页面部分内容导出生成word文档?
jsp页面导出为word文件需要利用apache的POI来完成。
核心代码如下:其实如果用框架做就方便多了,比如Struts2。
在Action里直接写如下代码: if(out!=null){ String fileName=""; fileName+="评价报告.doc"; try { HttpServletResponse response = ServletActionContext.getResponse(); response.setHeader("Content-disposition","attachment; filename="+new String(fileName.getBytes("GB2312"), "8859_1")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } out是jsp页面表单元素,一个button,用于提交表单到相应Action进行Word下载。
Action设置jsp页面头文件。
这样每次点击button就可以把相应jsp页面的内容保存到Word中并且支持下载,Word中内容并且是可编辑状态。
如何在JSP页面实现Word文件的预览
你的目的是想用word来浏览jsp文件内容吗?似乎没这种必要吧。
如果真想这么做的话,你可以先通过记事本、editplus等文件编辑工具打开jsp文件,然后复制粘贴到word文档中。
或者,你是想用word作为网页编辑器来打开它?word可以作为网页编辑器,在打开htm/html静态网页时没问题。
但是对于jsp这种动态类型的网页,它应该是支持得不好,会存在打不开的情况,有的打开了也可能显示不完全。
...
jsp 如何实现文件上传和下载功能?
上传: MyjspForm mf = (MyjspForm) form;// TODO Auto-generated method stub FormFile fname=mf.getFname(); byte [] fn = fname.getFileData(); OutputStream out = new FileOutputStream("D:\\"+fname.getFileName()); Date date = new Date(); String title = fname.getFileName(); String url = "d:\\"+fname.getFileName(); Upload ul = new Upload(); ul.setDate(date); ul.setTitle(title); ul.setUrl(url); UploadDAO uld = new UploadDAO(); uld.save(ul); out.write(fn); out.close(); 下载: DownloadForm downloadForm = (DownloadForm)form; String fname = request.getParameter("furl"); FileInputStream fi = new FileInputStream(fname); byte[] bt = new byte[fi.available()]; fi.read(bt); //设置文件是下载还是打开以及打开的方式msdownload表示下载;设置字湖集,//主要是解决文件中的中文信息 response.setContentType("application/msdownload;charset=utf-8"); //文件下载后的默认保存名及打开方式 String contentDisposition = "attachment; filename=" + "java.txt"; response.setHeader("Content-Disposition",contentDisposition); //设置下载长度 response.setContentLength(bt.length); ServletOutputStream sos = response.getOutputStream(); sos.write(bt); return null;
在jsp中,用流上传文档为什么是空的?
需要写一个servlet来处理上传的文件,你可以修改保存路径或选择将图片保存在数据库中,只需要做简单的修改就行了,servlet代码如下:package com.ek.servlet; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import com.ek.image.ImageUtil; publicclass FileUploadServlet extends HttpServlet { /** * */privatestaticfinallong serialVersionUID = 1L; privatestatic String filePath = ""; /** * Destruction of the servlet. */publicvoid destroy() { super.destroy(); // Just puts "destroy" string in log// Put your code here } /** * The doPost method of the servlet. * * This method is called when a form has its tag value method equals to * post. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */publicvoid doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html; charset=utf-8"); DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(4096); // the location for saving data that is larger than getSizeThreshold() factory.setRepository(new File(filePath)); ServletFileUpload upload = new ServletFileUpload(factory); // maximum size before a FileUploadException will be thrown upload.setSizeMax(1000000); try { List fileItems = upload.parseRequest(req); Iterator iter = fileItems.iterator(); // Get the file name String regExp = ".+\\\\(.+\\.?())$"; Pattern fileNamePattern = Pattern.compile(regExp); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { String name = item.getName(); long size = item.getSize(); if ((name == null || name.equals("")) && size == 0) continue; Matcher m = fileNamePattern.matcher(name); boolean result = m.find(); if (result) { try { // String type =// m.group(1).substring(m.group(1).lastIndexOf('.')+1); InputStream stream = item.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] b = newbyte[1000]; while (stream.read(b) > 0) { baos.write(b); } byte[] imageByte = baos.toByteArray(); String type = ImageUtil.getImageType(imageByte); if (type.equals(ImageUtil.TYPE_NOT_AVAILABLE)) thrownew Exception("file is not a image"); BufferedImage myImage = ImageUtil .readImage(imageByte); // display the image ImageUtil.printImage(myImage, type, res .getOutputStream()); // save the image// if you want to save the file into database, do it here// when you want to display the image, use the method printImage in ImageUtil item.write(new File(filePath + "\\" + m.group(1))); stream.close(); baos.close(); } catch (Exception e) { e.printStackTrace(); } } else { throw new IOException("fail to upload"); } } } } catch (IOException e) { e.printStackTrace(); } catch (FileUploadException e) { e.printStackTrace(); } } /** * Initialization of the servlet. * * @throws ServletException * if an error occure */ public void init() throws ServletException { // Change the file path here filePath = getServletContext().getRealPath("/"); } } servlet中使用到一个ImageUtil类,其中封装了图片处理的实用方法,用于读写图片,代码如下:package com.ek.image; import java.awt.Component; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.awt.MediaTracker; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.PixelGrabber; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.MemoryCacheImageInputStream; import net.jmge.gif.Gif89Encoder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.sun.imageio.plugins.bmp.BMPIma...
为什么我编的.js文件不能被jsp引用,如果把代码放在jsphe?
使用java中的io进行读取BufferedReader bufferedReader = null;File file = new File("文档地址+文档名.docx");if(!file.exists()){System.out.println("文件不存在");} else {bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "读取的字符格式(UTF-8或GBK)"));String lineText = null;while((lineText = bufferedReader.readLine()) != null){if (linText != null && !lineText.eq("")){System.out.println("一次读取一行,一行内容为:" + lineText);}}}
转载请注明出处51数据库 » 用jsp上传word文档代码
説好的25905213