【Java.ThirdParty】Apache Commons —— FileUpload —— web应用上传文件

来源:互联网 发布:淘宝轮胎3c认证怎么办 编辑:程序博客网 时间:2024/04/28 04:48

相关资料

参考地址:

http://commons.apache.org/proper/commons-fileupload/

Maven:

<dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version></dependency>


FileUpload 依赖于 Commons IO;

Commons FileUpload

The Commons FileUpload package makes it easy to add robust, high-performance, file upload capability to your servlets and web applications.

FileUpload parses HTTP requests which conform to RFC 1867, "Form-based File Upload in HTML". That is, if an HTTP request is submitted using the POST method, and with a content type of "multipart/form-data", then FileUpload can parse that request, and make the results available in a manner easily used by the caller.

通过web form向服务器上传文件的示例如下:通过向web服务器发送一个multipart/from-data请求

<!DOCTYPE html><html><head><meta charset="utf-8"><title>Upload Files</title></head><body>    <form method="post" enctype="multipart/form-data" action="uploadfile">    File Upload Testing:<br/>    Upload File 1: <input type="file" name="file1" size="30"/><br/>    Upload File 2: <input type="file" name="file2" size="30"/><br/>    <input type="submit" name="submit" value="Upload"/>    <input type="reset" name="reset" value="Reset"/>    </form></body></html>

FileUpload可以解析http request成为一个item list,其中每个item不管其底层具体是什么,都实现了FileItem接口。

传统的FileUpload API假定上传的文件一定会被保存在某个地方;通常为了更多的性能考虑或者灵活性,我们可以使用Streaming API,具体参考commons fileupload在线文档。

在Servlet中使用FileUpload - Save To Disk

创建一个Servlet如下:

package com.gof.test.servlet;import java.util.List;import java.util.Iterator;import java.io.IOException;import java.io.PrintWriter;import java.io.File;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.FileCleanerCleanup;import org.apache.commons.fileupload.servlet.ServletFileUpload;import org.apache.commons.fileupload.FileItem;import org.apache.commons.io.FileCleaningTracker;public class UploadFileServlet extends HttpServlet {/** *  */private static final long serialVersionUID = 3396770132755929933L;private String filePath = null;private String tempFilePath = null;    public void init(ServletConfig config) throws ServletException {        super.init(config);                // get the property in servlet configuration in web.xml         filePath = getInitParameter("filePath");        tempFilePath = getInitParameter("tempFilePath");        // get the real path is disk        filePath = getServletContext().getRealPath(filePath);        tempFilePath = getServletContext().getRealPath(tempFilePath);    }protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{    PrintWriter out = resp.getWriter();    // For Chinese File Name    req.setCharacterEncoding("utf-8");    // Begin to parse the uploaded filestry{    DiskFileItemFactory factory = new DiskFileItemFactory();    // Set the factory constraints    // Set the buffer size for file upload when write to disk    factory.setSizeThreshold(4 * 1024);    // Set the temporary path    factory.setRepository(new File(tempFilePath));            // Create a new file upload handler    ServletFileUpload upload = new ServletFileUpload(factory);    // Set overall request size constraint    upload.setFileSizeMax(4 * 1024 * 1024);    // Parse the request    List<FileItem> items = upload.parseRequest(req);    // Process the uploaded items    Iterator<FileItem> iter = items.iterator();    while (iter.hasNext()){    FileItem item = iter.next();        if (item.isFormField()){    processFormFields(item, out);    }else{    processUploadFiles(item, out);    }    }        out.close();}catch (Exception e){e.printStackTrace();}    }private void processFormFields(FileItem item, PrintWriter out){String name = item.getFieldName();String value = item.getString();out.println("The file name is " + name + "; The value is " + value);}private void processUploadFiles(FileItem item, PrintWriter out) throws Exception{String fieldName = item.getFieldName();String fileName = item.getName();String contentType = item.getContentType();long sizeInBytes = item.getSize();if ((fileName == null) || (sizeInBytes == 0)){return;}// write the file to diskFile uploadedFile = new File(filePath + "/" + fileName);item.write(uploadedFile);out.println("The file " + fileName + " is saved; The size of the file is " + sizeInBytes + " bytes");}}

在web.xml中配置上面的Servlet:

  <!-- test upload file: http://localhost:8080/base-webapp/uploadfile.html -->  <servlet>  <servlet-name>uploadfiletest</servlet-name>  <servlet-class>com.gof.test.servlet.UploadFileServlet</servlet-class>  <init-param>      <param-name>filePath</param-name>      <param-value>/upload</param-value>  </init-param>  <init-param>      <param-name>tempFilePath</param-name>      <param-value>/tempupload</param-value>  </init-param>  </servlet>  <servlet-mapping>      <servlet-name>uploadfiletest</servlet-name>      <url-pattern>/uploadfile</url-pattern>  </servlet-mapping>

当点击Upload按钮时,对应的文件将被保存到webapp下的目录/upload,同时临时文件夹/tempupload的文件会被删除;如果对传入的文件没有做相应的处理,则临时文件夹下的文件不会被删除。


资源清理(临时目录)






0 0
原创粉丝点击