Android for analog form upload

Source: Internet
Author: User

A long time ago, wrote an article about the download: based on the HTTP protocol download function implementation, today for Android file upload, also simple to mention two. On Android, the general use of HTTP simulation form or FTP file upload, using the FTP protocol, you can directly use the Appache ftpclient, the use of the method is very simple, no longer repeat. Here is the main explanation of the HTTP simulation form upload implementation.

Simulation form upload, in fact, is also very simple, the main need in the HTTP POST data body to build form information (multipart/form), form data format specification, you can refer to the REC standard. The following is an example of a format:

       ...
Content-type:multipart/form-data, boundary=------webkitformboundaryk7ck1eeropvuf1de
       content-length:145000
... ------webkitformboundaryk7ck1eeropvuf1de Content-disposition:form-data; name= "Filekey"; filename= " Bg_entry.png " Content-type:image/png DATA of FILE
       ------webkitformboundaryk7ck1eeropvuf1de--

The form request focuses on two parts:

Header:

1. Notify server via Content-type This is a form submission request and declares the boundary that you are using. Boundary is equivalent to a delimiter used to mark the beginning and end of form data.

2. The length of the Post body (including the length of the uploaded file) is told by Content-length the data length of the request.

Body:

1. Split the form data with boundary.

2. The form parameter is equivalent to a simple header, which generally includes two fields of content-disposition (file information) and Content-type (data type).

3. Each part, each field should be separated by CRLF.

4. End the form request with boundary plus "--".

The core code is as follows:

    protectedString doupload (httpurlconnection connection, Uploadparam param)throwsException {String Path=Param.getpath (); String Filekey= Textutils.isempty (Param.getfilekey ())? "File": Param.getfilekey (); String FileName=Param.getfilename (); String FileType= Textutils.isempty (Param.getcontenttype ())?MIME_TYPE_ALL:param.getContentType (); DataOutputStream Outs=NULL; BufferedReader ins=NULL; FileInputStream Fouts=NULL; String Response=NULL; Try {            //Content-disposition:form-data, name= "Filekey"; filename= "Bg_entry.png"//Content-type:image/pngStringBuilder Builder =NewStringBuilder (Buildparams (Param.getparams ())); Builder.append (Getboundaryprefixed ()). Append (CRLF). Append (String.Format (Header_con Tent_disposition+ colon_space + form_data + semicolon_space +filename, filekey, filename)                    . Append (CRLF). Append (Header_content_type). Append (FileType). Append (CRLF) //Must jump to new line to indicate the beginning of data.. Append (CRLF); byte[] Headbuf =builder.tostring (). GetBytes (Charset_utf8); //Must jump to new line to indicate the end of data.            byte[] Tailbuf = (CRLF + getboundaryprefixed () + Boundary_prefix +CRLF). GetBytes (Charset_utf8); LongCurrentbytes = 0; File File=NewFile (path); LongTotalSize = file.length () + Headbuf.length +tailbuf.length; //generally speaking,files larger than 4M should use streaming mode.            if(TotalSize > 4 * 1024 * 1024) {                //Avoid Oom when post large file. Ether is OK.Connection.setchunkedstreamingmode (1024);//Connection.setfixedlengthstreamingmode (totalsize);} connection.setrequestproperty (Header_content_length, string.valueof (totalsize)); Connection.connect ();Outs=NewDataOutputStream (Connection.getoutputstream ());            Outs.write (HEADBUF); Currentbytes+=headbuf.length;            UpdateProgress (Currentbytes, totalsize); Fouts=Newfileinputstream (file); byte[] buffer =New byte[1024]; intLength =-1; LongStartTime =System.currenttimemillis (); Longnow = 0;  while(length = fouts.read (buffer))! =-1) {                if(Length > 0) {outs.write (buffer,0, length); Currentbytes+=length; now=System.currenttimemillis (); if(Now-starttime >=progress_rate)                        {updateprogress (currentbytes, totalsize); StartTime=Now ; }                }                if(!Canrun ()) {                    Throw NewException ("Upload cancelled");            }} outs.write (TAILBUF);            Outs.flush ();            UpdateProgress (TotalSize, totalsize);            Fouts.close (); Fouts=NULL; //Response.            if(Connection.getresponsecode ()! = 200) {                Throw NewIllegalStateException (String.Format ("Error upload response:code:%s msg:%s", Connection.getresponsecode (), Connection.getresponsemessage ())); } INS=NewBufferedReader (NewInputStreamReader (Connection.getinputstream ()));            String Line; StringBuffer b=NewStringBuffer ();  while(line = Ins.readline ())! =NULL) {b.append (line); if(!Canrun ()) {                    Throw NewException ("Upload cancelled"); }} Response=b.tostring (); if(Textutils.isempty (response)) {Throw NewNullPointerException ("Null response:" +response);            } outs.close (); Outs=NULL;            Ins.close (); INS=NULL; } finally {            if(Fouts! =NULL) {fouts.close (); Fouts=NULL; }            if(Outs! =NULL) {outs.close (); Outs=NULL; }            if(INS! =NULL) {ins.close (); INS=NULL; }        }        returnresponse; }

The main steps are:

1. Configure Header Parameters

2. Building form Parameters

3. Read and send file contents

4. Get the response code

It is worth noting that, in general, the upload will read all the contents of the file into memory and then unified send, if the file is too large, it may cause memory overflow. So when judging if the file content is larger than 4MB, use chunked mode or stream mode to avoid oom.

            if (TotalSize > 4 * 1024x768 * 1024x768) {                //Avoid oom when post large file. Ether is OK.                Connection.setchunkedstreamingmode (1024x768);                 //Connection.setfixedlengthstreamingmode (totalsize);            }

For more code details, please refer to: transferlibrary--an Android file transfer library, the main implementation of HTTP-based file upload and download, simple and convenient, support multi-task download, breakpoint continuation and so on, welcome small partners to use communication: D

Android for analog form 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.