SPRINGMVC with Ajaxfileupload asynchronous multi-file upload to remote server

Source: Internet
Author: User

<input type= "File" id= "playeraddress" name= "playeraddress"/><input type= "file" id= "cover" name= "Cover"/> Here is the two file ID defined by itself
$.ajaxfileupload ({url:web_path+ ' upload/upload.do ', Secureuri:false, data:data,//the data JSON format to be passed Fileelem    Entid: [' playeraddress ', ' cover '], DataType: ' json ', ' success:function ' (data) {////////////post-upload callback. }, Error:function (data) {}});
/**     *     *      * @ param request     *  @param  response     *   @param  audioItem     *  @return      */      @RequestMapping (value =  "/upload.do", method = {  requestmethod.post })      @ResponseBody     public string  addmusic (httpservletrequest request,             httpservletresponse response, audioitem audioitem)  {         //There's no need to bother, it's just         string uploadfileurl  = globalutil .getvalue ("Upload_audioitem_audio_url");         string uploadiconurl =&nbsp Globalutil.getvalue ("Upload_audioitem_pic_url");         Commonsmultipartresolver resolver = new commonsmultipartresolver (                 request.getservletcontext ());         if  (Resolver.ismultipart (request))  {             multiparthttpservletrequest multirequest =   (multiparthttpservletrequest)  request;             //  get all the file names in the request              Iterator<string> iter = multirequest.getfilenames ();             while  (Iter.hasnext ())  {             &nbSp;   string filename = iter.next ();                 //  get uploaded files                  multipartfile file = multirequest.getfile (fileName);                 /**                  *  Get file name                  */                 String  Originalfilename = file.getoriginalfilename ();                                  if  ("Playeraddress". Equals (FileName) &&! "". Equals (originalfilename))  {                     try {                         //here the upload method is to use the HTTP  post the way to upload files   post them later                          String url =  Baseservice.upload (uploadfileurl,                                  file.getoriginalfilename (),                                  file.getinputstream ());                     } catch  (Ioexception e)  {                         // TODO Auto-generated catch block                          e.printstacktrace ();                     }                 }                 if  ("Cover". Equals (FileName) &&! "". Equals (OriginalFilename)) {&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp;               try {                          string icon = baseservice.upload (uploadIconUrl,                                  file.getoriginalfilename (),                                  file.getinputstream ());                     }  catch  (ioexception e)  {                &Nbsp;        // todo auto-generated catch block                          e.printstacktrace ();                     }                 }             }            //need attention here   Using ajaxfileupload requires that you return results using the following methods   success  methods              response.setcontenttype ("text/html");               try {                 Response.getwriter (). Write ("OK");             }  catch  (ioexception e)  {                 e.printstacktrace ();             }        }         return null;    }
The last step is      public static string upload (string httpurl,  String filename, inputstream inputstream)  {         String result =  "";        try {             //here to see your network environment   set proxy on Demand    normal no need to ignore              if  (True)  {                 system.setproperty (" Http.proxyhost ",  baseservice.proxy_ip);                 system.setproperty ("Http.proxyport",  baseservice.proxy_port);             }             string boundary =  "---------7d4a6d158c9"; //  define data dividers              url url = new url (Httpurl);             HttpURLConnection conn =  (httpurlconnection)   Url.openconnection ();            //  The Send POST request must have the following two lines set             conn.setdooutput (True) ;             conn.setdoinput (True);             conn.setusecaches (False);             conn.setrequestmethod ("POST");             conn.setrequestproperty ("Connection",  "keep-alive");         &Nbsp;   conn.setrequestproperty ("User-agent",                      "mozilla/4.0  (compatible;  MSIE&NBSP;6.0;&NBSP;WINDOWS&NBSP;NT&NBSP;5.1;&NBSP;SV1) ");             conn.setrequestproperty ("Charsert",  "UTF-8");             conn.setrequestproperty ("Content-type",                      "Multipart/form-data ;  boundary= " + boundary);             outputstream out = new dataoutputstream (Conn.getoutputstream ());             byte[] end_data =  ("\r\n--"  +  boundary +  "--\r\n"). GetBytes ();//  define the final data divider line              Stringbuilder sb = new stringbuilder ();             sb.append ("---");             sb.append (boundary);             sb.append ("\ r\n ");             sb.append (" Content-Disposition:  form-data;name=\ "File"  + 1                     +  "\"; filename=\ ""  + filename +   "\" \ \ \ \ \ \ "            sb.append (" content-type:application/octet-stream\r\n\r\n ");             byte[] data = sb.tosTring (). GetBytes ();             out.write (data);             DataInputStream in =  New datainputstream (InputStream);             Int bytes = 0;            byte[]  bufferOut = new byte[1024];             while  ((Bytes = in.read (bufferout))  != -1)  {                 out.write (bufferOut, 0,  bytes);            }             out.write ("\ r \ n". GetBytes ()); //  multiple files, add this   between two files     &nbSp;      in.close ();             out.write (End_data);             Out.flush ();             out.close ();             //  define BufferedReader input stream to read the response of the URL              BufferedReader reader = new  BufferedReader (New inputstreamreader (                     conn.getinputstream ()));             String line = null;             while  ((Line = reader.readline ())  != null)  {                result+=line;             }        } catch   (exception e)  {             SYSTEM.OUT.PRINTLN ("Send POST request exception!") " + e);        }             return new jsonobject (Result). getString ("url");     }//  It's over! I hope I can help you.


SPRINGMVC with Ajaxfileupload asynchronous multi-file upload to remote server

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.