commons-fileupload实现单次上传文件(word文档)
首先是这个文件需要用到的maven包
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>portlet-api</groupId> <artifactId>portlet-api</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.2</version> </dependency>
然后是servlet实现代码
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); //1、创建一个DiskFileItemFactory工厂 DiskFileItemFactory factory=new DiskFileItemFactory(); //创建解析器 ServletFileUpload upload=new ServletFileUpload(factory); upload.setHeaderEncoding("utf-8"); factory.setSizeThreshold(1024*500);//内存极限值 File linshi = new File("E:\\linshi");//暂时使用硬盘来解决内存不足的存储问题 factory.setRepository(linshi);//设置过大的读取路径 upload.setSizeMax(1024*1024*5);//设置最大值 try { List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { // 若是一个一般的表单域, 打印信息 if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString("utf-8"); System.out.println(name + ": " + value); } // 若是文件域则把文件保存到 e:\\files 目录下. else { String fileName = item.getName(); InputStream in = item.getInputStream(); fileName=(new Date()).getTime()+""; String fileUrl = "E:/files/" + fileName+".docx";//文件最终上传的位置 OutputStream out = new FileOutputStream(fileUrl); int len=0; byte buffer[] = new byte[1024]; //字节流保护文档的完整.不可以使用高级流 while((len=in.read(buffer))>0){ out.write(buffer, 0, len); } out.close(); in.close(); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } }