HttpClient structure File Upload

Source: Internet
Author: User
Tags getmessage throw exception

In the project we sometimes need to use other third-party APIs, and some APIs require us to upload files, search, the results are recorded here!

Meaning enctype= "multipart/form-data" description:
Upload files via HTTP protocol overview of RFC1867 protocol, JSP application example, the client sends content constructs

1, overview in the initial HTTP protocol, there is no upload file features. rfc1867 (http://www.ietf.org/rfc/rfc1867.txt) adds this functionality to the HTTP protocol. Client-side browsers, such as Microsoft IE, Mozila, Opera, etc., follow this specification to send user-specified files to the server. Server-side web-based programs, such as PHP, ASP, JSP, etc., can be in accordance with this specification, the user sent to resolve the file. Microsoft IE, Mozila, Opera has supported this protocol by using a special form on the Web page to send files. The vast majority of HTTP servers, including Tomcat, already support this protocol and can accept files that are sent. A variety of Web-page programs, such as PHP, ASP, JSP, for uploading files have done a good package.

2, upload the file instance, JSP example:

1 <formAction= "Gerry/publish/file"enctype= "Multipart/form-data"Method= "POST">2File<inputtype= "File"name= "File"/><BR/>3 <inputtype= "Submit"value= "Submit"/>4 </form>
View Code

If we upload a file, we must set the enctype to "Multipart/form-data", which means we are uploading a binary data stream.

3. Resolve this request in servlet

1         BooleanIsmultipart =servletfileupload.ismultipartcontent (req);2         if(Ismultipart) {3             //constructs a File upload processing object4Fileitemfactory factory =Newdiskfileitemfactory ();5Servletfileupload upload =Newservletfileupload (factory);6 7 Iterator items;8             Try {9                 //parse all file content submitted in the formTenItems =upload.parserequest (req). iterator (); One                  while(Items.hasnext ()) { AFileitem item =(Fileitem) Items.next (); - System.out.println (Item.getfieldname ()); - System.out.println (Item.isformfield ()); the System.out.println (item.getstring ()); -  -                     if(!Item.isformfield ()) { -                         //Remove the file name of the uploaded file +String name =item.getname (); -                         //get the storage path after uploading the file +String fileName = name.substring (name.lastindexof (' \ \ ') + 1, Name.length ()); A                         //storage path After uploading a file atString Path = Req.getrealpath ("file") + File.separatorchar +FileName; -  -                         //Uploading Files -File Uploaderfile =NewFile (path); - Item.write (uploaderfile); -                     } in                 } -}Catch(Exception e) { toResp.getoutputstream (). Write ("Throw exception" +e.getmessage ()). GetBytes ()); +             } -}Else { theResp.getoutputstream (). Write ("is not the This file upload". GetBytes ()); *}
View Code

The Servletfileupload Parserequest method allows you to parse both the file stream and the non-file stream. Do not consider the data flow format in HttpServletRequest.

4. Parse this request in spring

In spring we can get the file stream information in the request directly through Multipartfile.

1@RequestMapping (value = "/gerry/publish/file")2 @ResponseBody3      PublicString upload1 (multipartfile file) {4String OriginalFilename =file.getoriginalfilename ();5String FileName =file.getname ();6 System.out.println (originalfilename);7 System.out.println (fileName);8 System.out.println (File.getcontenttype ());9         Try {Ten Myhttpclient.addpic (File.getbytes ()); One}Catch(Exception e) { A             return"Failure, the exception msg is:" +e.getmessage (); -         } -         return"Success"; the}
View Code

5, the code constructs the HttpClient request, transmits the file

1 /**2 * Transfer file stream BS3      * 4      * @paramBS5 * stream of files to be transferred6      */7      Public Static voidAddpic (byte[] BS) {8HttpClient HttpClient =Newdefaulthttpclient ();9HttpPost HttpPost =Newhttppost (URL);Tenmultipartentity entity =Newmultipartentity (); OneEntity.addpart ("Pic",NewBytearraybody (BS, "pic")); A         Try { -             //add additional parameters, can be multiple/0 -Entity.addpart ("Name",NewStringbody ("liuming92"));  the}Catch(unsupportedencodingexception E1) { -             Throw NewRuntimeException (E1); -         } - httppost.setentity (entity); +         Try { -HttpResponse HttpResponse =Httpclient.execute (httppost); +             if(HttpResponse! =NULL) { AString result =entityutils.tostring (Httpresponse.getentity ()); at System.out.println (result); -             } -}Catch(IOException e) { -             Throw NewRuntimeException (e); -         } -}
View Code

In this location, uploading files in Java and transferring files to third parties are implemented.

HttpClient structure File Upload

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.