Java web开发中文件上传是比较经常使用的功能,例如论坛注册的时候上传几K的图片做为头像。前段时间信手翻了翻架子上的书,看到servlet3.0新特性当中有对文件上传功能的支持,随便写写servlet 3.0当中的Part和common-fileupload的ServletFileUpload。 html
html的<input type = "file" ...>标签表示文件域,能够在页面上产生一个文本框和一个文件选择按钮,要实现文件上传功能,该标签须要配置enctype属性,一般的配置是:<form method = "post" action = "#" enctype = "multipart/form-data"></form>
java
再来讲说Part,每个Part对象对应着一个文件上传域,Part对象提供了许多访问上传文件属性的方法,并提供write(String file)方法用于把上传的文件写入服务器硬盘。 web
能够在web.xml中经过<multipart-config>对上传参数进行配置,servlet配置: 服务器
<servlet> <servlet-name>uploadFile</servlet-name> <servlet-class>test.testFileUpload.com.UploadFileAction</servlet-class> <multipart-config> <max-file-size>1024000</max-file-size> </multipart-config> </servlet>
Part对象经过request对象获取文件上传域,经过write(String path)方法把文件写入到指定路径。上传action部分代码:
post
public void doServices(HttpServletRequest request, HttpServletResponse response) throws IOException{ Part part = null ; try { part = request.getPart("uploadFile"); } catch (IllegalStateException | ServletException e) { e.printStackTrace(); } String fileName = request.getParameter("fileName"); String path = getServletContext().getRealPath("/uploadFiles")+"/"+fileName; part.write(path); }
而后再说说ServletFileUpload,common-fileupload须要和common-io配套使用,一般通须要经过DiskFileItemFactory设置上传文件临时存储路径、文件存储路径、上传文件大小限制等,经过ServletFileUpload对象的parseRequest方法获取FileItem对象列表,而后遍历列表获取form上传域。文件上传Action代码以下:
spa
public void doServices(HttpServletRequest request, HttpServletResponse response){ DiskFileItemFactory factory = new DiskFileItemFactory(); String tmpPath = getServletContext().getRealPath("/uploadFilesTmp")+"/";//临时路径 String path = getServletContext().getRealPath("/uploadFiles")+"/";//文件存储路径 factory.setRepository(new File(tmpPath)); factory.setSizeThreshold(1024*1024); //缓冲区大小 ServletFileUpload servletFileUpload = new ServletFileUpload(factory); servletFileUpload.setFileSizeMax(-1);//设置上传文件大小 try { List<FileItem> fileItemList = servletFileUpload.parseRequest(request); for(FileItem fileItem : fileItemList){ if((!fileItem.isFormField())&&(fileItem.getSize()>0)){ String clientPath = fileItem.getName(); clientPath.replaceAll("\\\\", "/"); String clientFileName = clientPath.substring(clientPath.lastIndexOf("/")+1); System.out.println(clientFileName); File storeInServerFile = new File(path+"temp"); fileItem.write(storeInServerFile); }else{} } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }