Android batch file upload (Android batch image upload)

Source: Internet
Author: User

Many of the projects in the use of file bulk upload function, today just solve the problem, written in this, for future reference. First, bulk file uploads under the following schema may fail or not succeed: 1.android client +SPRINGMVC Server: server-side with ORG.SPRINGFRAMEWORK.WEB.MULTIPART.MULTIPARTHTTPSERVL Etrequest as a batch upload receive class, this combination of batch file upload will fail, the end server will only accept a file, that will only accept the first file.             There may be a problem with bulk uploads because Multiparthttpservletrequest encapsulates the original HttpServletRequest class of the servlet. 2.android Client +strutsmvc server: This collocation under the multi-file upload, I did not personally try, do not comment. If a netizen uses this way to upload the failure, the reason may be the same as 1.


The following shows the successful upload scenario: Use Android client +servlet (httpservletrequest) for file upload. the servlet-side code is as follows:

      

Diskfileitemfactory factory = new Diskfileitemfactory (); Servletfileupload upload = new Servletfileupload (factory); Try{list items = upload.parserequest (request); Iterator ITR = Items.iterator (); while (Itr.hasnext ()) {Fileitem item = (Fileitem) itr.next (); if (Item.isformfield ()) { System.out.println ("form argument name:" + item.getfieldname () + ", form parameter value:" + item.getstring ("UTF-8"));} Else{if (Item.getname ()! = null &&!item.getname (). Equals ("")) {System.out.println ("size of uploaded file:" + item.getsize () ); System.out.println ("Type of upload file:" + Item.getcontenttype ()),//Item.getname () returns the full path name of the uploaded file on the client System.out.println (" The name of the uploaded file: "+ item.getname ()); File Tempfile = new file (Item.getname ());//The Save path of the uploaded file = "new" (Sc.getrealpath ("/") + Savepath, Tempfile.getname ()); Item.write (file); Request.setattribute ("Upload.message", "Upload file successful!") ");} Else{request.setattribute ("Upload.message", "no option to upload files!") ");}}}} catch (Fileuploadexception e) {e.printstacktrace ();} catch (Exception e) {e.printstacktrace (); Request.setattribute (" Upload. Message "," Upload file failed! ");} Request.getrequestdispatcher ("/uploadresult.jsp"). Forward (request, response);

The Android Terminal code is as follows:

public class Sockethttprequester {/** * multi-File Upload * directly through the HTTP protocol to submit data to the server, the implementation of the following form submission function: * <form method=post AC tion= "Http://192.168.1.101:8083/upload/servlet/UploadServlet" enctype= "Multipart/form-data" > <input type= "Text" name= "NAME" > <input type= "text" name= "id" > <input type= "file" Name= "ImageFile"/&G            T <input type= "file" name= "Zip"/> </FORM> * @param path upload path (note: Avoid path tests such as localhost or 127.0.0.1, as it will point to Phone Simulator, you can use http://www.iteye.cn or http://192.168.1.101:8083 path test) * @param params request parameter key is parameter name, value is parameter value * @param f Ile Upload file */public static Boolean post (String path, map<string, string> params, formfile[] files) throws Exce  ption{Final String boundary = "---------------------------7da2137580612";//Data Separator line final string endline        = "--" + Boundary + "--\r\n";//Data end flag int filedatalength = 0; for (Formfile uploadfile:files) {//Get the total length of file type data            StringBuilder Fileexplain = new StringBuilder ();             Fileexplain.append ("--");             Fileexplain.append (boundary);             Fileexplain.append ("\ r \ n"); Fileexplain.append ("content-disposition:form-data;name=\" "+ uploadfile.getparametername () +" \ "; filename=\" "+             Uploadfile.getfilname () + "\" \ \ "\ \ \");             Fileexplain.append ("Content-type:" + uploadfile.getcontenttype () + "\r\n\r\n");             Fileexplain.append ("\ r \ n");            Filedatalength + = Fileexplain.length ();             if (Uploadfile.getinstream ()!=null) {filedatalength + = Uploadfile.getfile (). Length ();             }else{Filedatalength + = Uploadfile.getdata (). length;        }} StringBuilder textentity = new StringBuilder ();            For (map.entry<string, string> entry:params.entrySet ()) {//Construct the Entity data of the text type parameter Textentity.append ("--");            Textentity.append (boundary);       Textentity.append ("\ r \ n");     Textentity.append ("Content-disposition:form-data;            Name=\ "" + entry.getkey () + "\" \r\n\r\n ");            Textentity.append (Entry.getvalue ());        Textentity.append ("\ r \ n"); }//Calculate the total length of entity data transferred to the server int datalength = textentity.tostring (). GetBytes (). length + filedatalength + endline.ge                Tbytes (). length;        URL url = new URL (path); int port = Url.getport () ==-1?        80:url.getport ();                   Socket socket = new Socket (Inetaddress.getbyname (Url.gethost ()), port);        OutputStream OutStream = Socket.getoutputstream ();        The following completes the sending of the HTTP request header String Requestmethod = "POST" + url.getpath () + "http/1.1\r\n";        Outstream.write (Requestmethod.getbytes ()); String accept = "Accept:image/gif, Image/jpeg, Image/pjpeg, Image/pjpeg, Application/x-shockwave-flash, application/ Xaml+xml, Application/vnd.ms-xpsdocument, APPLICATION/X-MS-XBAP, Application/x-ms-application, application/ Vnd.ms-excel, Application/vnd.ms-powerpoint, APPLIcation/msword, */*\r\n ";        Outstream.write (Accept.getbytes ());        String language = "accept-language:zh-cn\r\n";        Outstream.write (Language.getbytes ()); String contenttype = "CONTENT-TYPE:MULTIPART/FORM-DATA;        boundary= "+ boundary+" \ r \ n ";        Outstream.write (Contenttype.getbytes ());        String contentlength = "Content-length:" + datalength + "\ r \ n";        Outstream.write (Contentlength.getbytes ());        String alive = "connection:keep-alive\r\n";        Outstream.write (Alive.getbytes ());        String host = "Host:" + url.gethost () + ":" + port + "\ r \ n";        Outstream.write (Host.getbytes ());        After the HTTP request header is written, write a carriage return outstream.write ("\ r \ n") according to the HTTP protocol. GetBytes ());                   Send the Entity data of all text types Outstream.write (textentity.tostring (). GetBytes ());             Send Entity data for all file types out for (Formfile uploadfile:files) {StringBuilder fileentity = new StringBuilder ();             Fileentity.append ("--"); Fileentity.append (BOundary);             Fileentity.append ("\ r \ n"); Fileentity.append ("content-disposition:form-data;name=\" "+ uploadfile.getparametername () +" \ "; filename=\" "+             Uploadfile.getfilname () + "\" \ \ "\ \ \");             Fileentity.append ("Content-type:" + uploadfile.getcontenttype () + "\r\n\r\n");             Outstream.write (Fileentity.tostring (). GetBytes ());                 if (Uploadfile.getinstream ()!=null) {byte[] buffer = new byte[1024];                 int len = 0;                 while (len = Uploadfile.getinstream (). Read (buffer, 0, 1024x768)) (!=-1) {outstream.write (buffer, 0, Len);             } uploadfile.getinstream (). Close ();             }else{Outstream.write (Uploadfile.getdata (), 0, Uploadfile.getdata (). length);        } outstream.write ("\ r \ n". GetBytes ());                }//below sends the end of data flag indicating that the data has ended Outstream.write (Endline.getbytes ()); BufferedReader reader = new BufferedReader (New INputstreamreader (Socket.getinputstream ()));        if (Reader.readline (). IndexOf ("200") ==-1) {//Read the data returned by the Web server, determine if the request code is 200, if not 200, on behalf of the request failed to return false;        } outstream.flush ();        Outstream.close ();        Reader.close ();        Socket.close ();    return true; /** * Single File Upload * submit data to Server * @param path upload path (note: Avoid path tests such as localhost or 127.0.0.1, as it will point to the phone simulator, you can use the http://www . itcast.cn or http://192.168.1.10:8080 path test) * @param params request parameter key is parameter name, value is parameter value * @param file Upload */PU Blic static Boolean post (String path, map<string, string> params, formfile file) throws exception{return post    (Path, params, new formfile[]{file}); }}


The code for the Formfile class is as follows

public class Formfile {/* * Upload the file data */private byte[] data;    Private InputStream instream;        private file file;    private int fileSize;    /* File name */private String filname;    /* Request Parameter name */private String parametername;        /* Content Type */private String ContentType = "Application/octet-stream";        Public Formfile (String filname, byte[] data, String parametername, String contentType) {this.data = data;        This.filname = Filname;        This.parametername = parametername;    if (contenttype!=null) This.contenttype = ContentType; Public Formfile (String filname, File file, String parametername, String contentType) {this.filname = Filn        Ame        This.parametername = parametername;        This.file = file;        try {this.instream = new FileInputStream (file);        } catch (FileNotFoundException e) {e.printstacktrace ();    } if (contenttype!=null) This.contenttype = ContentType; } PUBlic formfile (inputstream instream, int fileSize, String filname,string parametername, string contentType) {super (); . instream = Instream;this.filesize = Filesize;this.filname = Filname;this.parametername = ParameterName;        This.contenttype = ContentType;} public int GetFileSize () {return fileSize;}    Public file GetFile () {return file;    } public InputStream Getinstream () {return instream;    } public byte[] GetData () {return data;    } public String Getfilname () {return filname;    } public void Setfilname (String filname) {this.filname = Filname;    } public String Getparametername () {return parametername;    } public void SetParameterName (String parametername) {this.parametername = parametername;    } public String getContentType () {return contentType;    } public void setContentType (String contentType) {this.contenttype = ContentType; }    }

Note: The above Android upload code is borrowed from the Internet, thanks to the original author! The above code after I test, can be a normal multi-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.