Android uploads files over http

Source: Internet
Author: User

Generally, the maximum size of files uploaded over http is 2 MB, which is suitable for uploading files smaller than 2 MB [Code] [Java] code 001 import java. io. file; 002 import java. io. fileInputStream; 003 import java. io. fileNotFoundException; 004 import java. io. inputStream; 005006/** 007 * uploaded file 008 */009 public class FormFile {010/** uploaded file data */011 private byte [] data; 012 private InputStream inStream; 013 private File file; 014/** File name */015 private String filname; 016/** request parameter name */017 private String ParameterName; 018/** content type */019 private String contentType = "application/octet-stream "; 020/** 021*022 * @ param filname file name 023 * @ param data file data uploaded 024 * @ param parameterName parameter 025 * @ param contentType content type 026 */027 public formFile (String filname, byte [] data, String parameterName, String contentType) {028this. data = data; 029this. filname = filname; 030this. parameterName = parameterName; 031if (cont EntType! = Null) this. contentType = contentType; 032} 033/** 034*035 * @ param filname file name 036 * @ param file the uploaded file 037 * @ param parameterName parameter 038 * @ param contentType content type 039 */040 public FormFile (String filname, file file, String parameterName, String contentType) {041this. filname = filname; 042this. parameterName = parameterName; 043this. file = file; 044try {045this. inStream = new FileInputStream (file); 046} ca Tch (FileNotFoundException e) {047e. printStackTrace (); 048} 049if (contentType! = Null) this. contentType = contentType; 050} 051052 public File getFile () {053 return file; 054} 055056 public InputStream getInStream () {057 return inStream; 058} 059060 public byte [] getData () {061 return data; 062} 063064 public String getFilname () {065 return filname; 066} 067068 public void setFilname (String filname) {069this. filname = filname; 070} 071072 public String getParameterName () {073 return para MeterName; 074} 075076 public void setParameterName (String parameterName) {077this. parameterName = parameterName; 078} 079080 public String getContentType () {081 return contentType; 082} 083084 public void setContentType (String contentType) {085this. contentType = contentType; 086} 087088} 089090/** 091 * submit data directly to the server over HTTP, as shown in the following form submission function: 092 * <form method = post action = "http: // 192.168.0.200: 8080/ssi/fileload/t Est. do "enctype =" multipart/form-data "> 093 <input type =" text "NAME =" name "> 094 <input type =" text "NAME =" id "> 095 <input type = "file" name = "imagefile"/> 096 <input type = "file" name = "zip"/> 097 </FORM> 098 * @ param path upload path (note: 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.xxx.cn or http: // 192.168.1.10: 8080) 099 * @ param params the request parameter key is the parameter name, and the value is the parameter value 100 * @ param file Upload file 101 */102 public static boole An post (String path, Map <String, String> params, FormFile [] files) throws Exception {103 final String BOUNDARY = "------------------------- 7da1_7580612 "; // data separation line 104 final String endline = "--" + BOUNDARY + "-- \ r \ n"; // data end mark 1050000int fileDataLength = 0; mandatory for (FormFile uploadFile: files) {// obtain the total length of the file type data 108 StringBuilder fileExplain = new StringBuilder (); optional fileExplain. append ("--"); 110 fileExpla In. append (BOUNDARY); 111fileExplain. append ("\ r \ n"); Specify fileexplain. append ("Content-Disposition: form-data; name = \" "+ uploadFile. getParameterName () + "\"; filename = \ "" + uploadFile. getFilname () + "\" \ r \ n "); 113fileExplain. append ("Content-Type:" + uploadFile. getContentType () + "\ r \ n"); 114fileExplain. append ("\ r \ n"); 115 fileDataLength + = fileExplain. length (); when if (uploadFile. getInStream ()! = Null) {117 fileDataLength + = uploadFile. getFile (). length (); 118} else {119 fileDataLength + = uploadFile. getData (). length; 120} 121} 122 StringBuilder textEntity = new StringBuilder (); 123for (Map. entry <String, String> entry: params. entrySet () {// construct object data of the text type parameter 124textEntity. append ("--"); 125textEntity. append (BOUNDARY); 126textEntity. append ("\ r \ n"); extends textentity. append ("Content-Disposition: form-data; nam E = \ "" + entry. getKey () + "\" \ r \ n "); 128textEntity. append (entry. getValue (); 129textEntity. append ("\ r \ n"); 130} 131 // calculate the total length of the object data transmitted to the server: 132int dataLength = textEntity. toString (). getBytes (). length + fileDataLength + endline. getBytes (). length; 133134URL url = new URL (path); 135int port = url. getPort () =-1? 80: url. getPort (); 136 Socket socket = new Socket (InetAddress. getByName (url. getHost (), port); 137 OutputStream outStream = socket. getOutputStream (); 138 // The HTTP request header is sent below 139 String requestmethod = "POST" + url. getPath () + "HTTP/1.1 \ r \ n"; 140outStream. write (requestmethod. getBytes (); 141 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 "; 142outStream. write (accept. getBytes (); 143 String language = "Accept-Language: zh-CN \ r \ n"; 144outStream. write (language. getBytes (); 145 String contenttype = "Content-Type: multipart/form-data; boundary =" + BOUNDARY + "\ r \ n "; 146outStream. write (contenttype. getBytes (); 147 String contentlength = "Content-Length:" + dataLength + "\ r \ n"; 148outStream. write (contentlength. getBytes (); 149 String alive = "Connection: Keep-Alive \ r \ n"; 150outStream. write (alive. getBytes (); 151 String host = "Host:" + url. getHost () + ":" + port + "\ r \ n"; 152outStream. write (host. getBytes (); 153 // After writing the HTTP Request Header, write another carriage return line 154outStream Based on the HTTP protocol. write ("\ r \ n ". getBy Tes (); 155 // send object data of all text types to 156outStream. write (textEntity. toString (). getBytes (); 157 // send object data of all file types to 158for (FormFile uploadFile: files) {159 StringBuilder fileEntity = new StringBuilder (); 160fileEntity. append ("--"); 161fileEntity. append (BOUNDARY); 162fileEntity. append ("\ r \ n"); 163fileEntity. append ("Content-Disposition: form-data; name = \" "+ uploadFile. getParameterName () + "\"; filename = \ "" + uploadFil E. getFilname () + "\" \ r \ n "); 164fileEntity. append ("Content-Type:" + uploadFile. getContentType () + "\ r \ n"); 165outStream. write (fileEntity. toString (). getBytes (); 166if (uploadFile. getInStream ()! = Null) {167 byte [] buffer = new byte [1024]; 168int len = 0; 169 while (len = uploadFile. getInStream (). read (buffer ))! =-1) {170outStream. write (buffer, 0, len); 171} 172uploadFile. getInStream (). close (); 173} else {174outStream. write (uploadFile. getData (), 0, uploadFile. getData (). length); 175} 176outStream. write ("\ r \ n ". getBytes (); 177} 178 // The End mark of the sent data, indicating that the data has ended 179outStream. write (endline. getBytes (); 180181 BufferedReader reader = new BufferedReader (newInputStreamReader (socket. getInputStream (); 182if (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, the request fails. 183 return false; 184} 185outStream. flush (); 186outStream. close (); 187reader. close (); 188socket. close (); 189 return true; 190} 191192/** 193 * submit data to the server 194 * @ 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.xxx.cn or http: // 192.168.1.10: 8080) 195 * @ param params request parameter key for the parameter name, value is the parameter value 196 * @ param file Upload file 197 */198 public static boolean post (String path, Map <String, String> params, FormFile file) throws Exception {199 return post (path, params, new FormFile [] {file}); 200}

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.