Springmvc uploading files to the service-side interface using HttpPost

Source: Internet
Author: User

Now the wide use of spring so that we do not need to do file upload data transcoding, multipartentity encapsulated in a variety of methods, We can instantiate the Multipartentity class directly on the client to write the file that needs to be uploaded as a parameter to the HttpPost entity, which is similar to using form form submission on the front end to implement file uploads, The difference is the front end we are setting the enctype= "Multipart/form-data" parameter in the form. Needless to say, here is the code; The first is the client:
ImportJava.io.File; Importjava.io.IOException; Importorg.apache.http.HttpEntity; ImportOrg.apache.http.HttpResponse; ImportOrg.apache.http.HttpStatus; Importorg.apache.http.ParseException; Importorg.apache.http.client.HttpClient; ImportOrg.apache.http.client.methods.HttpPost; Importorg.apache.http.entity.mime.MultipartEntity; ImportOrg.apache.http.entity.mime.content.FileBody; Importorg.apache.http.impl.client.DefaultHttpClient; Importorg.apache.http.util.EntityUtils; Public classfileuploadclient { Public voidsubmitpost (string url, String File36path, String File48path, String File72path, String File96path, String File144path) {HttpClient HttpClient=Newdefaulthttpclient (); Try{httppost HttpPost=Newhttppost (URL); Filebody File36=NewFilebody (NewFile (File36path)); Filebody file48=NewFilebody (NewFile (File48path)); Filebody file72=NewFilebody (NewFile (File72path)); Filebody file96=NewFilebody (NewFile (File96path)); Filebody file144=NewFilebody (NewFile (File144path)); Multipartentity reqentity=Newmultipartentity (); Reqentity.addpart ("File36", file36);//File36 is the file upload of the request background;Reqentity.addpart ("File48", file48); Reqentity.addpart ("File72", file72); Reqentity.addpart ("File96", file96); Reqentity.addpart ("File144", file144);            Httppost.setentity (reqentity); HttpResponse Response=Httpclient.execute (HttpPost); intStatusCode =response.getstatusline (). Getstatuscode (); if(StatusCode = =HTTPSTATUS.SC_OK) {System.out.println ("Server normal response ..."); Httpentity resentity=response.getentity (); System.out.println (entityutils.tostring (resentity));//HttpClient comes with the tool class to read the returned dataSystem.out.println (Resentity.getcontent ());//here is the return value of the service sideEntityutils.consume (resentity); }        } Catch(ParseException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } finally {            Try{Httpclient.getconnectionmanager (). Shutdown (); } Catch(Exception ignore) {}}} /**     * @paramargs*/     Public Static voidMain (string[] args) {//TODO auto-generated Method Stubfileuploadclient fileuploadclient=Newfileuploadclient (); Fileuploadclient.submitpost ("Http://127.0.0.1:8080/testProject/pictureUploadInterface.htm","C://app_icon1.png", "C://app_icon2.png", "C://app_icon3.png", "C://app_icon4.png", "C://app_icon5.png"); }}
As for the service side, as spring implements
/*** Image Upload Interface * *@paramRequest *@paramResponse *@paramSession *@return     * @throwsIOException*/@RequestMapping (Value= "/pictureuploadinterface", method =requestmethod.post) PublicString Pictureuploadinterface (httpservletrequest request, httpservletresponse response, HttpSession Sessio N, @RequestParam ("File36") Multipartfile File36, @RequestParam ("File48") Multipartfile file48, @RequestParam ("File72") Multipartfile file72, @RequestParam ("File96") Multipartfile file96, @RequestParam ("File144") multipartfile file144)throwsIOException {String FilePath= "D://test"; //Responding to clientsResponse.setcontenttype ("text/html"); PrintWriter out=Response.getwriter (); if(File36.isempty () &&File48.isempty ()&& file72.isempty () && file96.isempty () &&File144.isempty ()) {Out.write (-102);//-102 images uploaded are all empty            return NULL; }        if((game==NULL|| Game.equals ("")) | | (channel==NULL)|| Channel.equals ("") {out.write (-100);//-100 parameter error            return NULL; }                if(!File36.isempty ()) {            if(!filenameutils.getextension (File36.getoriginalfilename ()). Equalsignorecase ("PNG") {out.write (-101);//-101 Picture Format error                return NULL; } Else{String path= FilePath + file.separator + "drawable-ldpi" + file.separator + "App_icon.png"; byte[] File36byte =file36.getbytes (); Fileutils.writebytearraytofile (NewFile (path), file36byte); Out.write (200); }        }        if(!File48.isempty ()) {            if(!filenameutils.getextension (File48.getoriginalfilename ()). Equalsignorecase ("PNG") {out.write (-101); return NULL; } Else{String path= FilePath + file.separator + "drawable" + file.separator + "App_icon.png"; byte[] File48bype =file48.getbytes (); Fileutils.writebytearraytofile (NewFile (path), file48bype); }        }        if(!File72.isempty ()) {            if(!filenameutils.getextension (File72.getoriginalfilename ()). Equalsignorecase ("PNG") {out.write (-101); return NULL; } Else{String path= FilePath + file.separator + "drawable-hdpi" + file.separator + "App_icon.png"; byte[] File72byte =file72.getbytes (); Fileutils.writebytearraytofile (NewFile (path), file72byte); }        }        if(!File96.isempty ()) {            if(!filenameutils.getextension (File96.getoriginalfilename ()). Equalsignorecase ("PNG") {out.write (-101); return NULL; } Else{String path= FilePath + file.separator + "drawable-xhdpi" + file.separator + "App_icon.png"; byte[] File96byte =file96.getbytes (); Fileutils.writebytearraytofile (NewFile (path), file96byte); }        }        if(!File144.isempty ()) {            if(!filenameutils.getextension (File144.getoriginalfilename ()). Equalsignorecase ("PNG") {out.write (-101); return NULL; } Else{String path= FilePath + file.separator + "drawable-xxhdpi" + file.separator + "App_icon.png"; byte[] File144byte =file144.getbytes (); Fileutils.writebytearraytofile (NewFile (path), file144byte); }} out.write (200);//200 uploading pictures successfullyOut.close (); return NULL; }


The JDR package is needed here

Httpclient-4.2.jar

Httpclient-cache-4.2.jar

Httpcore-4.2.jar

Httpmime-4.2.jar

Commons-logging-1.1.1.jar

Springmvc uploading files to the service-side interface using HttpPost

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.