FileUpload框架实现文件上传(多个文件)和下载
一、文件上传:
对于大文件执行下面的代码之间卡死
package com.example.web.service.servlet; import java.io.File; import java.io.IOException; import java.util.List; 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.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class FileUpload extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); String dir = request.getSession().getServletContext().getRealPath("/files"); File dirFile= new File(dir); if(!dirFile.exists()) dirFile.mkdirs(); for (FileItem fileItem : items) { //文本类型 if(fileItem.isFormField()){ String name =fileItem.getFieldName(); String value=fileItem.getString(); System.out.println(" name: "+name+" value: "+value); }else { System.out.println(" 上传文件目录: "+dir); File saveFile = new File(dir,fileItem.getName()); fileItem.write(saveFile); } } } catch (Exception e) { e.printStackTrace(); } } }
jsp界面,上传文件时form表单必须有 enctype="multipart/form-data"
<form action="<%=request.getContextPath() %>/FileUpload" method="post" enctype="multipart/form-data"> <input type="text" name="name" > <br> <input type="file" name="file1"> <br> <input type="file" name="file2"> <br> <input type="submit" value=" submit "> </form>