Android Batch File Upload (android batch Image Upload)

Source: Internet
Author: User

The batch file upload function is often used in the project. This problem is solved today and can be written here for future reference. First, batch file upload in the following architecture may fail or fail: 1. android client + springMVC server: the server uses org. springframework. web. multipart. multipartHttpServletRequest is used as the batch upload receiving class. In this case, the batch file upload fails. In the end, the server receives only one file, that is, only the first file is accepted. MultipartHttpServletRequest may encapsulate the servlet's original HttpServletRequest class, resulting in problems with batch upload. 2. android client + strutsMVC server: in this case, I did not try it myself and did not comment on it. If a netizen fails to upload the file in this way, the cause may be the same as 1.


Next, we will describe how to upload files successfully: using the android client + Servlet (HttpServletRequest. The Servlet 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 parameter name:" + item. getFieldName () + ", form parameter value:" + item. getString ("UTF-8");} else {if (item. getName ()! = Null &&! Item. getName (). equals ("") {System. out. println ("Size of the uploaded file:" + item. getSize (); System. out. println ("File Upload type:" + item. getContentType (); // item. getName () returns the complete path name of the uploaded file on the client System. out. println ("Name of the uploaded file:" + item. getName (); File tempFile = new File (item. getName (); // save path of the uploaded File file File = new File (SC. getRealPath ("/") + savePath, tempFile. getName (); item. write (file); request. setAttribute ("upload. message "," File Uploaded successfully! ");} Else {request. setAttribute (" upload. message "," No file upload is selected! ") ;}}} Catch (FileUploadException e) {e. printStackTrace ();} catch (Exception e) {e. printStackTrace (); request. setAttribute ("upload. message "," An error occurred while uploading the file! ");} Request. getRequestDispatcher ("/uploadResult. jsp "). forward (request, response );

The android code is as follows:

Public class SocketHttpRequester {/*** Multifile upload * submits data directly to the server through the HTTP protocol. The following form submission function is implemented: ** @ param path: avoid using a path test like localhost or 127.0.0.1 because it will point to the phone simulator and you can use a path test like http://www.iteye.cn or http: // 192.168.1.101: 8083) * @ param params the request parameter key is the parameter name, and value is the parameter value * @ param file Upload file */public static boolean post (String path, Map
 
  
Params, FormFile [] files) throws Exception {final String BOUNDARY = "--------------------------- 7da1_7580612 "; // data separation line final String endline = "--" + BOUNDARY + "-- \ r \ n"; // data end mark int fileDataLength = 0; for (FormFile uploadFile: files) {// obtain the total length of the file type data StringBuilder fileExplain = new StringBuilder (); fileExplain. append ("--"); fileExplain. append (BOUNDARY); fileExplain. append ("\ r \ n"); fileExplain. appen D ("Content-Disposition: form-data; name = \" "+ uploadFile. getParameterName () + "\"; filename = \ "" + uploadFile. getFilname () + "\" \ r \ n "); fileExplain. append ("Content-Type:" + uploadFile. getContentType () + "\ 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
  
   
Entry: params. entrySet () {// construct the object data textEntity of the text type parameter. append ("--"); textEntity. append (BOUNDARY); textEntity. append ("\ r \ n"); textEntity. append ("Content-Disposition: form-data; name = \" "+ entry. getKey () + "\" \ r \ n "); textEntity. append (entry. getValue (); textEntity. append ("\ r \ n");} // calculates the total length of the object data transmitted to the server. int dataLength = textEntity. toString (). getBytes (). length + fileDataLength + endline. getBytes (). len Response; 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 String requestmethod = "POST" + url sent in the HTTP request header is completed below. 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, applica Tion/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 (contenttyp E. 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 writing the HTTP Request Header, write another carriage return outStream Based on the HTTP protocol. write ("\ r \ n ". getBytes (); // send object data of all text types out of outStream. write (textEn Tity. toString (). getBytes (); // send object data of 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 () + "\" \ r \ n "); fileEntity. append ("Content-Type:" + uploadFi Le. getContentType () + "\ 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, 1024 ))! =-1) {outStream. write (buffer, 0, len);} uploadFile. getInStream (). close ();} else {outStream. write (uploadFile. getData (), 0, uploadFile. getData (). length);} outStream. write ("\ r \ n ". getBytes ();} // The End mark of the sent data below, 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 and determine whether the request code is 200. If it is not 200, return false for request failure;} outStream. flush (); outStream. close (); reader. close (); socket. close (); return true;}/*** upload a single file ** submit data to the server * @ param path upload path (Note: Do not test using a path such as localhost or 127.0.0.1, because it will point to the phone simulator, you can test using a path like http://www.itcast.cn or http: // 192.168.1.10: 8080) * @ param params request parameter key for Parameter Name, value is the parameter value * @ param file Upload file */public static boolean post (String path, Map
   
    
Params, FormFile file) throws Exception {return post (path, params, new FormFile [] {file });}}
   
  
 


The FormFile class code is as follows:

Public class FormFile {/* Upload 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 = filn Ame; this. parameterName = parameterName; if (contentType! = Null) this. contentType = contentType;} public FormFile (String filname, File file, String parameterName, String contentType) {this. filname = filname; 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 (); this. 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 client upload code is borrowed from the internet. I would like to thank the original author! The above code is tested by myself and can be uploaded to multiple files normally.

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.