一.需要引入两个jar包

commons-fileupload-1.2.2.jar

commons-io-2.4.jar

二.编写对应jsp页面

 <div>
     <form action="UploadFileServlet" method="post" enctype="multipart/form-data">  
        选择文件:<input type="file" name="file" width="120px">  
        <input type="submit" value="上传">  
    </form>   
    </div>   

三.编写对应的Servlet代码

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@WebServlet("/UploadFileServlet")
public class UploadFileServlet extends HttpServlet {
  private static final String UPLOAD_DIRECTORY = "upload";
  private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
  private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
  private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    doPost(req, resp);
}
  @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
      req.setCharacterEncoding("utf-8");
      DiskFileItemFactory factory = new DiskFileItemFactory();
      factory.setSizeThreshold(MEMORY_THRESHOLD);
      factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
      ServletFileUpload upload = new ServletFileUpload(factory);
      upload.setFileSizeMax(MAX_FILE_SIZE);
      upload.setSizeMax(MAX_REQUEST_SIZE);
      String uploadPath = getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;
      File uploadDir = new File(uploadPath);
      if (!uploadDir.exists()) {
          uploadDir.mkdir();
      }
      try {
          @SuppressWarnings("unchecked")
          List<FileItem> formItems = upload.parseRequest(req);
          if (formItems != null && formItems.size() > 0) {
              for (FileItem item : formItems) {
                  if (!item.isFormField()) {
                      String fileName = new File(item.getName()).getName();
                      String filePath = uploadPath + File.separator + fileName;
                      File storeFile = new File(filePath);
                      System.out.println(filePath);
                      item.write(storeFile);
                      req.setAttribute("message",
                          "文件上传成功!");
                  }
              }
          }
      } catch (Exception ex) {
          req.setAttribute("message",
                  "错误信息: " + ex.getMessage());
      }
      req.getRequestDispatcher("ShowServlet").forward(req, resp);  
  }  
}

 

posted on 2017-08-17 16:44  blythe  阅读(105)  评论(0编辑  收藏  举报