1. Guide Package
2. Core class: Multipartrequest
Multipartrequest is the packaging class for request
Parameter 1:request
Parameter 2: Save path
Parameter 3: Upload file size, default is 1M
Parameter 4: Encoding
Parameter 5: Rename filerenamepolicy, the default renaming format is to add a number after the name
Parameters can be used as needed
3, compared with apache-upload
1, can upload multiple files directly, without traversing
2, get text and other simple text without judgment
3, can be named by default
4. Demo
1String Path=getservletcontext (). Getrealpath ("File");2Filerenamepolicy rename=NewDefaultfilerenamepolicy ();//Renamed By default, followed by name: name. jpg, name 1.jpg, name 2.jpg3Multipartrequest req=NewMultipartrequest (Request, Path, 1024*1024*10, "Utf-8"), rename);4 5 //Get upload file information6Response.setcontenttype ("Text/html;charset=utf-8");7PrintWriter out=Response.getwriter ();8Out.write ("File name:" +req.getoriginalfilename ("file"));9Out.write ("<br/> new filename:" +req.getfilesystemname ("file"));TenOut.write ("<br/> file type: +req.getcontenttype")); OneOut.write ("<br/> Size:" +req.getfile ("file"). Length ()); AOut.write ("<br/> Description:" +req.getparameter ("desc")); -Out.write ("</img> "); -
In the above code, if the upload is a Chinese named picture, it will not display properly, so we need to rename, implement the Filerenamepolicy interface
1 classMyrenameImplementsFilerenamepolicy2 {3 Publicfile Rename (file file) {4String filename=file.getname ();5String extname=filename.substring (Filename.lastindexof (".")));6String Uuid=uuid.randomuuid (). toString (). Replace ("-", "" ");7String newname=uuid+Extname;8file=NewFile (File.getparent (), newName);9 returnfile;Ten } One A}
Call Rename
Multipartrequest req=Newnew myrename ());
Cos implementation file upload--recommended