1. File Upload
1. Modify the enctype of the form: <form action= "" method= "Post" enctype= "Multipart/form-data" > Modified servlet cannot pass REQ.GETP Arameter ("parameter name") accepts the request parameter 2. Import jar Package: Commons-fileupload-1.2.2.jar Commons-io-1.4.jar 3. Check method and Contenttyp E boolean ismultipart=servletfileupload.ismultipartcontent (req); if (!ismultipart) {return; 4. Create a factory object that handles Fileitem fileitemfactory factory=new diskfileitemfactory (); Create a Processor object that handles file uploads Servletfileupload upload=new servletfileupload (Factory); Parse Request Object List<fileitem> items=upload.parserequest (req); for (Fileitem fileitem:items) {String fieldname=fileitem.getfiledname (); if (Fileitem.isformfield ()) {String filename=fileitem.getstring ("Utf-8"); }else{String filename=fileitem.getname (); String Contenttype=fileitem.getcontenttype (); String Realpath=super.getservltcontext (). Getrealpath ("/upload"); FileiTem.write (New File (realpath+ "/" +filename)); }} 5. File name processing uses the UUID as the filename String uuid=uuid.randomuuid (). toString (); String extension=filenameutils.getextension (fileName); Filename=uuid+ "." Extension 6. Cache size and Temp directory settings cache size: Factory.setsizethreshold (500*1024); Set TEMP directory: Factory.setrepository (New File (""));
2. Uploading files using annotations
@MultipartConfig 可以通过req.getParamter()接受参数 接受上传文件 Part part=req.getPart(""); part.write(realPath+"/"+name);
3. File download
接受请求参数: String fileName=req.getParameter("fileName"); fileName=new String(fileName.getBytes("ISO-8859-1"),"utf-8"); 找到资源的位置,读取到内存,响应给浏览器: String realPath=super.getServletContext().getRealPath(""); String filePath=realPath+"\\"+fileName; ServletOutputStream out=resp.getOutputStream(); //设置响应头 resp.setContenType("application/x-msdownload"); //获取请求头信息Use-Agent String userAgent=req.getHeader("User-Agent"); if(userAgent.contain("MSIE")){ //IE fileName=URLEncoder.encode(fileName,"utf-8"); }else{ //W3C fileName=new String(fileName.getBytes("utf-8"),"ISO-8859-1"); } //设置下载的文件名称 resp.setHeader("Content-Disposition","attachment;fileName="+fileName); //将数据响应到浏览器 Files.copy(Paths.get(filePath),out);
9 file upload and download