JAVA commons-fileupload文件上传组件使用说明

准备工作:

相关文件下载:

1.commons-io-1.2.jar:http://apache.justdn.org/jakarta/commons/io/binaries/commons-io-1.2.zip 

2.commons-fileupload-1.1.1.jar:ftp://justdn.org/apache/jakarta/commons/fileupload/binaries/commons-fileupload-1.1.1.zip

 

servlet代码:

/**
 * Class Description:
 */
public class UploadFileServlet extends HttpServlet {
 private String uploadPath = "C://upload//"; // 上传文件的目录
 private String tempPath = "C://upload//tmp//"; // 临时文件目录
 static String filename = "0";
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  {
   String uploadPath = "C:/temp2/"; // 用于存放上传文件的目录
   String tempPath = "C:/temp"; // 用于存放临时文件的目录

   boolean isMultipart = FileUpload.isMultipartContent(request);
   if (!isMultipart) {
    return;
   }
   try {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(4096);
    factory.setRepository(new File(tempPath));

    // Create a new file upload handler
    FileUpload upload = new FileUpload(factory);

    // Set overall request size constraint
    upload.setSizeMax(1263509131 * 1024);

    List items = upload.parseRequest(request);
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
     FileItem item = (FileItem) iter.next();
     // 忽略其他不是文件域的所有表单信息
     if (!item.isFormField()) {
      String name = item.getName();
      name = name.substring(
        name.lastIndexOf(File.separator) + 1, name
          .length());
      filename = (Integer.parseInt(filename) + 1) + "";
      long size = item.getSize();
      if ((name == null || name.equals("")) && size == 0)
       continue;
      item.write(new File(uploadPath + filename));// 这里的路径你可以改成你感兴趣的地方
     }
    }

   } catch (Exception e) {
    // 可以跳转出错页面
    e.printStackTrace();
   }
   response.sendRedirect("index.html");

  }

 }
}

 

web.xml代码


  Upload
  
   UploadFileServlet
  

 

 
  Upload
  /fileupload
 

 

html页面:




New Document





enctype="multipart/form-data" name="form1">
 
 



 

将上面部署在一个web应用中就OK!

你可能感兴趣的:(JAVA commons-fileupload文件上传组件使用说明)