Android Volley parsing (iii) file upload

Source: Internet
Author: User

Before we talked about how to achieve form submission through volley, and this article with a link is very big, if not see a blog friends, it is recommended to first look at the Android Volley parsing (ii) Form submission
Because the file upload is essentially the form's submission, but it submits the data contains the file type, followed by the form submitted by the forms to analyze.

Data format

Here we through the picture upload case to analyze, other files are the same way of implementation; Here is the data format that I uploaded when I was uploading the map, first to analyze

POST http://chuantu.biz/upload.php http/1.1Host:chuantu.bizConnection:keep-aliveContent-length:4459Cache-control:max-age=0Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8Origin:http://chuantu.bizuser-agent:mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/40.0.2214.93 safari/537.36Content-type:multipart/form-data, boundary=----WEBKITFORMBOUNDARYS4NMHW9NB2EEUSLLReferer:http://chuantu.biz/accept-encoding:gzip, deflateAccept-language:zh-cn,zh;q=0.8Cookies:__cfduid=d9215d649e6e648e0eac7688b406a3d911425089350------WEBKITFORMBOUNDARYS4NMHW9NB2EEUSLLContent-Disposition:Form-data; Name="Uploadimg"; Filename="Spark_bg.png"Content-Type:Image/pngJFIFC%#, #& ') *) -0-(0% () (C((((((((((((((((((((((((((((((((((((((((((((((((((("}!1aqa"Q2#BR $3br%&' () *456789:cdefghijstuvwxyzcdefghijstuvwxyz w!1aqaq "2B #3Rbr $4%& '()*56789: cdefghijstuvwxyzcdefghijstuvwxyz? PNG------WEBKITFORMBOUNDARYS4NMHW9NB2EEUSLL--

It is not difficult to find that this format is very close to the form submission format, but there are some differences, here you can see the total plus the end line, there are five elements, because the garbled part, is actually the picture of the binary number, the whole line;
1, the first line: "--" + boundary + "\r\n" ;
The front also said that the file upload, in fact, is the form submission, so at the beginning of the submission of data mark unchanged;
2, the second line: Content-Disposition: form-data; name="参数的名称"; filename="上传的文件名" + "\r\n"
It's more than a regular form. filename= "uploaded file name";
3, the third line: Content-Type: 文件的 mime 类型 + "\r\n"
This line is required for file upload, and ordinary text submission is optional, MIME type needs to be based on the document query;
4, line fourth: "\r\n"
5, five lines 文件的二进制数据 + "\r\n" :
This is the same as the normal form submission;
End Line: "--" + boundary + "--" + "\r\n"
As you can see, the file Upload verse format is only two different from the form submitted in our last blog post, 1, the second row of time added a filename variable, 2, added a row Content-Type: 文件的 mime 类型 + "\r\n" ;
Files can also upload multiple files at the same time, upload multiple files when you repeat 1, 2, 3, 4, 5 steps, at the end of the last file to add a unified end line.

File entity class

Here is the picture operation so I built a formimg.java.

/** * Created by Moon.zhong on 2015/3/3. * * Public  class formimage {    //Name of the parameter    PrivateString Mname;//File name    PrivateString Mfilename;//MIME of file, need to query according to document    PrivateString Mmime;//need to upload the picture resources, because here testing for convenience, directly to the Bigmap pass in, really in the project generally do not do so, but the image of the path to pass over, here to the image of the binary conversion    PrivateBitmap Mbitmap; Public Formimage(Bitmap Mbitmap) { This. Mbitmap = Mbitmap; } PublicStringGetName() {//return mname;//test, write the parameter name to death        return "Uploadimg"; } PublicStringGetFileName() {//test, write the name of the dead file directly        return "Test.png"; }//Binary conversion of images     Public byte[]GetValue() {Bytearrayoutputstream BOS =NewBytearrayoutputstream (); Mbitmap.compress (Bitmap.CompressFormat.JPEG, the, BOS);returnBos.tobytearray (); }//Because I know it is a PNG file, so I check it directly according to the document     PublicStringGetmime() {return "Image/png"; }}
Volley encapsulation of File data
/** * Created by Gyzhong on 15/3/1. * *Public class postuploadrequest extends Request<String> {    /** * When correct data is returned with * /    PrivateResponselistener Mlistener;/ * Request data passed in as parameter * /    PrivateList<formimage> Mlistitem;PrivateString boundary ="--------------520-13-14";//Data separation line    PrivateString Multipart_form_data ="Multipart/form-data"; Public postuploadrequest (String URL, list<formimage> listItem, Responselistener listener) {Super(Method.post, URL, listener); This. Mlistener = Listener; Setshouldcache (false); Mlistitem = ListItem;//Set the response event for the request, because the file upload takes a long time, so it's increased here, set to 5 secondsSetretrypolicy (NewDefaultretrypolicy ( the, Defaultretrypolicy.default_max_retries,defaultretrypolicy.default_backoff_mult)); }/** * Start parsing data here * @param Response response from the network * @return  */    @Override    protectedResponse<string> parsenetworkresponse (Networkresponse Response) {Try{String mstring =NewString (Response.data, Httpheaderparser.parsecharset (response.headers)); LOG.V ("Zgy","====mstring==="+ mstring);returnResponse.success (mstring, Httpheaderparser.parsecacheheaders (Response)); }Catch(Unsupportedencodingexception e) {returnResponse.error (NewParseError (e)); }    }/** * Callback correct data * @param Response The parsed response returned by * *    @Override    protectedvoid Deliverresponse (String response) {mlistener.onresponse (response); }@OverridePublic byte[] GetBody ()throwsAuthfailureerror {if(Mlistitem = =NULL|| Mlistitem.size () = =0){return Super. GetBody (); } bytearrayoutputstream BOS =NewBytearrayoutputstream ();        int N = Mlistitem.size (); Formimage Formimage; for(int i =0;            i < N; i++) {formimage = Mlistitem.get (i); StringBuffer sb=NewStringBuffer ();/ * First line * /            //' "--" + boundary + "\ r \ n"Sb.append ("--"+boundary); Sb.append ("\ r \ n") ;/ * Second line * /            //content-disposition:form-data; name= "parameter name"; filename= "uploaded filename" + "\ r \ n "Sb.append ("Content-disposition:form-data;"); Sb.append (" name=\ " ");            Sb.append (Formimage.getname ()); Sb.append ("\"") ; Sb.append ("; Filename=\ "") ;            Sb.append (Formimage.getfilename ()); Sb.append ("\""); Sb.append ("\ r \ n") ;/ * Line three * /            //content-type: MIME type of file + "\ r \ n"Sb.append ("Content-type:");            Sb.append (Formimage.getmime ()); Sb.append ("\ r \ n") ;/ * Line Fourth * /            //"\ r \ n"Sb.append ("\ r \ n") ;Try{Bos.write (Sb.tostring (). GetBytes ("Utf-8"));/ * Line Fifth * /                //File binary data + "\ r \ n"Bos.write (Formimage.getvalue ()); Bos.write ("\ r \ n". GetBytes ("Utf-8")); }Catch(IOException e)            {E.printstacktrace (); }        }/ * End line * /        //' "--" + Boundary + "--" + "\ r \ n" 'String EndLine ="--"+ Boundary +"--"+"\ r \ n";Try{Bos.write (Endline.tostring (). GetBytes ("Utf-8")); }Catch(IOException e)        {E.printstacktrace (); } LOG.V ("Zgy","=====formimage====\n"+bos.tostring ());returnBos.tobytearray (); }//content-type:multipart/form-data, boundary=----------8888888888888    @OverridePublic String Getbodycontenttype () {returnmultipart_form_data+"; Boundary= "+boundary; }}

Because the code in the comments written in more detail, plus a lot of things in the previous blog has been said, so here directly on the code.

File Upload Interface
/** * Created by Moon.zhong on 2015/3/3. * * Public  class uploadapi {    /** * Upload Image interface * @param bitmap need to upload picture * @param Listener Request Callback */     Public Static void uploadimg(Bitmap Bitmap,responselistener Listener) {List<formimage> imageList =NewArraylist<formimage> (); Imagelist.add (NewFormimage (bitmap)); Request Request =NewPostuploadrequest (Constant.uploadhost,imagelist,listener);    Volleyutil.getrequestqueue (). Add (Request); }}
Image upload Verification

Upload class Postuploadactivity.java

/** * Created by Moon.zhong on 2015/3/2. * * Public  class postuploadactivity extends actionbaractivity {    PrivateTextView Mshowresponse;PrivateImageView Mimageview;PrivateProgressDialog Mdialog;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.LAYOUT.ACTIVITY_UPLOAD_IMG);        Mshowresponse = (TextView) Findviewbyid (r.id.id_show_response);        Mimageview = (ImageView) Findviewbyid (r.id.id_show_img); Mdialog =NewProgressDialog ( This) ; Mdialog.setcanceledontouchoutside (false); } Public void uploadimg(View view) {Mdialog.setmessage ("The picture crosses ...");        Mdialog.show ();        Bitmap Bitmap = Bitmapfactory.decoderesource (Getresources (), R.mipmap.logo); Uploadapi.uploadimg (Bitmap,NewResponselistener<string> () {@Override             Public void Onerrorresponse(Volleyerror error) {LOG.V ("Zgy","===========volleyerror========="+ERROR); Mshowresponse.settext ("errorresponse\n"+error.getmessage ()); Toast.maketext (postuploadactivity. This,"Upload failed", Toast.length_short). Show ();            Mdialog.dismiss (); }@Override             Public void Onresponse(String response) {response = response.substring (Response.indexof ("img src=")); Response = response.substring (8, Response.indexof ("/>")) ; LOG.V ("Zgy","===========onresponse========="+response); Mshowresponse.settext ("Picture address: \ n"+response);                Mdialog.dismiss (); Toast.maketext (postuploadactivity. This,"Upload succeeded", Toast.length_short). Show ();    }        }) ; }}

The test results are as follows:
Upload image page:

The picture crosses

Image upload successful, address is http://www.chuantu.biz/t/67/1425474351x-1376440163.png

Request via web page

Can see, volley implement file upload operation is very convenient, but, do not know if you see here there is no problem? In fact, volley implementation of the file upload is a big problem, what is the problem, we first think about it, I will be in the following article to talk about this problem, and provide solutions (is the follow-up, not the next article). Volley here, for its function is also said a large part, but there is a very useful point of knowledge not mentioned, that is volley caching mechanism, the next section, will open the volley cache trip, please look forward to!

Click to download the source code

Android Volley parsing (iii) file upload

Related Article

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.