Several common ways to upload files in Java

Source: Internet
Author: User

1, Servletfileupload

When the commit data type is multipare/form-data type in the form submission, if we use the servlet to do the processing, the HTTP request will be wrapped into a HttpServletRequest object by the servlet container.

, which is handled by the corresponding servlet.

 PackageCom.jws.app.operater.service.impl;ImportJava.io.File;ImportJava.util.HashMap;ImportJava.util.Iterator;Importjava.util.List;ImportJavax.annotation.Resource;Importjavax.servlet.http.HttpServletRequest;ImportOrg.apache.commons.fileupload.FileItem;Importorg.apache.commons.fileupload.FileItemFactory;Importorg.apache.commons.fileupload.disk.DiskFileItemFactory;ImportOrg.apache.commons.fileupload.servlet.ServletFileUpload;ImportOrg.apache.log4j.Logger;ImportOrg.springframework.stereotype.Service;ImportNet.sf.json.JSONObject;ImportCom.jws.app.operater.data.UserInfoMapper;ImportCom.jws.app.operater.model.UserInfo;ImportCom.jws.app.operater.service.PersionPhoteAuthServer;Importcom.jws.common.constant.Constants;ImportCom.jws.common.constant.ConstantsCode;ImportCom.jws.common.util.JiveGlobe;Importcom.jws.common.util.ResultPackaging; @Service ("Persionphoteauthserverimpl") Public classPersionphoteauthserverimplImplementsPersionphoteauthserver {@ResourcePrivateUserinfomapper Userinfomapper; Private FinalLogger Logger = Logger.getlogger ( This. GetClass ()); @Override Publicjsonobject Uploadphoto (httpservletrequest reques) {jsonobject returnobject=NewJsonobject (); String Path=Constants.imageurl; File Repositoryfile=NewFile (path); if(!repositoryfile.exists ())        {Repositoryfile.mkdirs ();} Fileitemfactory Factory=NewDiskfileitemfactory (1024 * 32, Repositoryfile); Servletfileupload Upload=Newservletfileupload (Factory); Upload.setheaderencoding ("Utf-8"); Upload.setsizemax (1024 * 1024 * 500); List<?> Fileitr =NULL; Try{Fileitr=upload.parserequest (reques); //speak non-file values in maphashmap<string, string> map =NewHashmap<>(); Iterator<?> iter =Fileitr.iterator ();  while(Iter.hasnext ()) {Fileitem Item=(Fileitem) iter.next (); if(Item.isformfield ()) {Map.put (Item.getfieldname (), item.getstring ()); }                }                //Validation Parameters                if(Map = =NULL|| !map.containskey ("OpenID") ) {Returnobject=resultpackaging.dealjsonobject (Constantscode.result_code_fail, Constantscode.code_lack_parameter,NULL); returnReturnobject; } String OpenID= Map.get ("OpenID"); //Working with Files                BooleanIsTrue =true; String filename= ""; Iterator<?> Iter1 =Fileitr.iterator ();  while(Iter1.hasnext ()) {Fileitem F=(Fileitem) iter1.next (); if(!F.isformfield ()) {                //details name=abc.png, size=376507 bytes, isformfield=false, Fieldname=picture1filename = f.getname () = =NULL? "": F.getname (); FileName= Jiveglobe.getfromrom () + ". jpg"; File SaveFile=NewFile (path, filename); if(Savefile.exists ()) {IsTrue=false; Break;}                        F.write (SaveFile); }             }            if(jiveglobe.isempty (filename)) {Returnobject=resultpackaging.dealjsonobject (Constantscode.result_code_fail, Constantscode.code_lack_parameter,NULL); returnReturnobject; } returnobject=resultpackaging.dealjsonobject (constantscode.result_code_success, Constantscode.result_code_success,NULL); //Save File InformationUserInfo rd =NewUserInfo (); Rd.setsparefield1 ("1");            RD.SETSPAREFIELD3 (filename);            Rd.setopenid (OpenID);        Userinfomapper.updatebyprimarykey (RD); } Catch(Exception e) {System.out.println (e); Logger.error ("# # #认证失败" +e); }        returnReturnobject; }        }
View Code

2, Multipartfile

@RequestMapping ("/upload") @ResponseBody PublicString Handlefileupload (@RequestParam ("File") multipartfile file) {if(File.isempty ()) {return"File is empty"; }        //Get file nameString FileName =File.getoriginalfilename (); System.out.println ("The uploaded file name is:" +fileName); //gets the suffix name of the fileString suffixname = filename.substring (Filename.lastindexof ("."))); System.out.println ("The name of the uploaded suffix is:" +suffixname); //the path after file uploadString FilePath = "d://"; File dest=NewFile (FilePath +fileName); //detect if a directory exists        if(!Dest.getparentfile (). exists ())        {Dest.getparentfile (). Mkdirs (); }        Try{File.transferto (dest); return"Upload succeeded"; } Catch(IllegalStateException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }        return"Upload Failed"; }
View Code
/*** Multiple Files specific upload time, mainly using multiparthttpservletrequest and multipartfile * *@paramRequest *@return     */@RequestMapping (Value= "/batch/upload", method =requestmethod.post) Public@ResponseBody String handleFileUpload1 (httpservletrequest request) {List<MultipartFile> files = ((multiparthttpservletrequest) request). GetFiles ("File"); String FilePath= "d://"; Multipartfile file=NULL;  for(inti = 0; I < files.size (); ++i) {file=Files.get (i); //Get file nameString FileName =File.getoriginalfilename (); System.out.println ("The uploaded file name is:" +fileName); if(!File.isempty ()) {File dest=NewFile (FilePath +fileName); //detect if a directory exists                if(!Dest.getparentfile (). exists ())                {Dest.getparentfile (). Mkdirs (); }                Try{File.transferto (dest); } Catch(Exception e) {return"Upload failed" + i + "= +" +E.getmessage (); }            } Else {                return"Upload failed" + i + "file is empty."; }        }        return"Upload succeeded"; }
View Code

3, Commonsmultipartresolver

  

*
* @param request
* @return
*/
@ResponseBody
@RequestMapping ("/uploadfile")
Public map<string, object> UploadFile (HttpServletRequest request) {
map<string, object> map = new hashmap<string, object> ();
Initializes the current context to commonsmutipartresolver (multipart parser)
Commonsmultipartresolver multipartresolver = new Commonsmultipartresolver (Request.getsession (). GetServletContext () );
Check if there is a enctype= "Multipart/form-data" in the form
if (Multipartresolver.ismultipart (request)) {
Change request to multi-part Request
Multiparthttpservletrequest multirequest = (multiparthttpservletrequest) request;
Get all the file names in Multirequest
Iterator iter = Multirequest.getfilenames ();
while (Iter.hasnext ()) {
Traverse all files at once
Multipartfile file = Multirequest.getfile (Iter.next (). toString ());
try {
if (file = null && Stringutils.isnotblank (File.getoriginalfilename (). Trim ())) {
map<string, string> metas = new hashmap<string, string> ();
Get file suffix
String filename = File.getoriginalfilename ();
String NewFileName = System.currenttimemillis () + (int) (Math.random () * 100)
+ filename.substring (Filename.lastindexof ("."));
Metas.put (Storageconstants.meta_key_filename, NewFileName);
String Imgurl = Storageservice.store (File.getbytes (), Metas);
Map.put ("Imgurl", Imgurl);
Map.put ("RetCode", "success");
Map.put ("Imgurl",
"Https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=611483611,2895064642&fm=117&gp=0.jpg");
}
} catch (Exception e) {
E.printstacktrace ();
}
}
} else {
Map.put ("RetCode", "error");
}
return map;

Several common ways to upload files in Java

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.