700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > commons-fileupload实现单次上传文件(word文档)

commons-fileupload实现单次上传文件(word文档)

时间:2024-04-04 02:09:49

相关推荐

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();} }

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。