Java uses Commons-fileupload components to implement file upload best practices

Source: Internet
Author: User

The goal of learningUsing Commons-fileupload to implement file uploads using the Commons-fileupload package File Upload Tool class What is Commons-fileupload? The commonsfileuploadpackage makes it easy-to-add robust, high-performance, file upload capability to your servlets and we b applications. FileUpload parses HTTP requests which conform TORFC 1867, "form-based File Upload in HTML". If an HTTP request is submitted using the POST method, and with a content type of "Multipart/form-data", then Fil Eupload can parse the request, and make the results available in a manner easily used by the caller. FileUpload package can easily add powerful, high performance, file upload capabilities to your servlet Web application. FileUpload parsing HTTP requests compliant with RFC 1867, "File uploads in HTML." That is, if an HTTP request is submitted using the Post method and is "Multipart/form-data" with a content type, then FileUpload can parse the request and provide the result with an easy-to-use calling method. Why to use Commons-fileuploadWhen using the traditional servlet upload, we can use Req.getinputstream () to get the stream of file upload, we need to manually deal with this stream after the flow to the flow of unnecessary start and end content, in order to really get the content of the stream , this section does not explore the upload of the original servlet, and we open another chapter to explore the original Servelt upload. requirements for using Commons-fileupload
    1. Method must be a post, not a get
    2. Add a new attribute enctype, with a value of "Multipart/form-data"
    3. File Form Item <input> type is file, i.e. type= "file"
use Commons-fileupload core steps to interpretStep one: Determine if file upload is possible second step: Create a Fileitem factory and upload the core components from the factory servletfileupload The third step: resolve the request requests by the core upload component to get all the form items of the form. Each form item in the form corresponds to a fileitem fourth step: Iterate through all the form items, judging whether it is a normal form item, and if it is not a file upload, you can perform a series of operations on the traversed Fileitem. Encapsulation of a tool class, let us in the process of file upload is cool and coolWe've covered the entire process of uploading files using commons-fileupload, so we've just encapsulated this process as a tool class that we use directly in a servlet that uploads to a file, Very convenient first step: Create a DTO (to store the results of the Commons-fileupload resolution request)
ImportOrg.apache.commons.fileupload.FileItem;ImportJava.util.HashMap;ImportJava.util.Map; Public classParamdto {PrivateMap<string,string>Parammap; PrivateMap<string,fileitem>Filemap;  Publicparamdto () {Parammap=NewHashmap<>(); Filemap=NewHashmap<>(); }      PublicMap<string, string>Getparammap () {returnParammap; }      Public voidSetparammap (map<string, string>Parammap) {         This. Parammap =Parammap; }      PublicMap<string, fileitem>Getfilemap () {returnFilemap; }      Public voidSetfilemap (map<string, fileitem>Filemap) {         This. Filemap =Filemap; }}

Step two: Encapsulate the entire request of Commons-fileupload parsing file into a tool class
ImportOrg.apache.commons.fileupload.FileItem;Importorg.apache.commons.fileupload.FileUploadException;Importorg.apache.commons.fileupload.disk.DiskFileItemFactory;ImportOrg.apache.commons.fileupload.servlet.ServletFileUpload;Importorg.imooc.dto.ParamDto;Importjavax.servlet.http.HttpServletRequest;ImportJava.io.File;Importjava.util.List; Public classRequestutil {/*** Parse parameters and uploaded files from the request stream *@paramRequest*/     Public Staticparamdto ParseParam (httpservletrequest request) {paramdto result=Newparamdto ();//Create a Fileitem factory create a file upload core component from a Diskfileitemfactory objectServletfileupload upload =NewServletfileupload (Newdiskfileitemfactory ()); Upload.setheaderencoding ("UTF-8"); Try {//resolve request requests through File Upload core component, get all Fileitem objectsList<fileitem> fileitemlist =upload.parserequest (request);//Traverse and manipulate all form items (fileitem) of a form             for(Fileitem fileitem:fileitemlist) {//Judge this form item if it is a normal form item                if(Fileitem.isformfield ()) {Result.getparammap (). Put (Fileitem.getfieldname (), Fileitem.getstring ("UTF-8"));//if it is not the normal text field of the form, it is}Else{Result.getfilemap (). Put (Fileitem.getfieldname (), Fileitem); }            }        } Catch(fileuploadexception e) {e.printstacktrace (); } Catch(Exception e) {e.printstacktrace (); }        returnresult; }}

Step three: Let's use this tool class directly in the servlet, haha another: we can certainly encapsulate a common method of saving a file (Item)
ImportOrg.apache.commons.fileupload.FileItem;ImportJava.io.File; Public classFileutil {/*** Save path of uploaded file*/     Public Static FinalString Save_path = "d:/upload/"; /*** Save uploaded files *@paramFileitem *@paramPath *@return     * @throwsException*/     Public StaticString Save (Fileitem fileitem,string path)throwsException {String fileName= System.currenttimemillis () + "_" +Fileitem.getname (); Fileitem.write (NewFile (path +fileName)); returnFileName; }}

All right, we'll see how the original file upload works when you're free.

Java uses Commons-fileupload components to implement file upload best practices

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.