Android使用http协议实现文件的上传


http协议上传文件一般最大是2M,比较适合上传小于两M的文件

下面是封装的一个文件类:

  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileNotFoundException;  
  4. import java.io.InputStream;  
  5.   
  6. /** 
  7.  * 上传的文件 
  8.  */  
  9. public class FormFile {  
  10.     /* 上传文件的数据 */  
  11.     private byte[] data;  
  12.     private InputStream inStream;  
  13.     private File file;  
  14.     /* 文件名称 */  
  15.     private String filname;  
  16.     /* 请求参数名称*/  
  17.     private String parameterName;  
  18.     /* 内容类型 */  
  19.     private String contentType = "application/octet-stream";  
  20.     /** 
  21.      *  
  22.      * @param filname 文件名称 
  23.      * @param data 上传的文件数据 
  24.      * @param parameterName 参数 
  25.      * @param contentType 内容类型 
  26.      */  
  27.     public FormFile(String filname, byte[] data, String parameterName, String contentType) {  
  28.         this.data = data;  
  29.         this.filname = filname;  
  30.         this.parameterName = parameterName;  
  31.         if(contentType!=nullthis.contentType = contentType;  
  32.     }  
  33.     /** 
  34.      *  
  35.      * @param filname 文件名 
  36.      * @param file 上传的文件 
  37.      * @param parameterName 参数 
  38.      * @param contentType 内容内容类型 
  39.      */  
  40.     public FormFile(String filname, File file, String parameterName, String contentType) {  
  41.         this.filname = filname;  
  42.         this.parameterName = parameterName;  
  43.         this.file = file;  
  44.         try {  
  45.             this.inStream = new FileInputStream(file);  
  46.         } catch (FileNotFoundException e) {  
  47.             e.printStackTrace();  
  48.         }  
  49.         if(contentType!=nullthis.contentType = contentType;  
  50.     }  
  51.       
  52.     public File getFile() {  
  53.         return file;  
  54.     }  
  55.   
  56.     public InputStream getInStream() {  
  57.         return inStream;  
  58.     }  
  59.   
  60.     public byte[] getData() {  
  61.         return data;  
  62.     }  
  63.   
  64.     public String getFilname() {  
  65.         return filname;  
  66.     }  
  67.   
  68.     public void setFilname(String filname) {  
  69.         this.filname = filname;  
  70.     }  
  71.   
  72.     public String getParameterName() {  
  73.         return parameterName;  
  74.     }  
  75.   
  76.     public void setParameterName(String parameterName) {  
  77.         this.parameterName = parameterName;  
  78.     }  
  79.   
  80.     public String getContentType() {  
  81.         return contentType;  
  82.     }  
  83.   
  84.     public void setContentType(String contentType) {  
  85.         this.contentType = contentType;  
  86.     }  
  87.       
  88. }  
下面的方法封装的http协议上传数据:
  1. /** 
  2.      * 直接通过HTTP协议提交数据到服务器,实现如下面表单提交功能: 
  3.      *   <FORM METHOD=POST ACTION="http://192.168.0.200:8080/ssi/fileload/test.do" enctype="multipart/form-data"> 
  4.             <INPUT TYPE="text" NAME="name"> 
  5.             <INPUT TYPE="text" NAME="id"> 
  6.             <input type="file" name="imagefile"/> 
  7.             <input type="file" name="zip"/> 
  8.          </FORM> 
  9.      * @param path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.xxx.cn或http://192.168.1.10:8080这样的路径测试) 
  10.      * @param params 请求参数 key为参数名,value为参数值 
  11.      * @param file 上传文件 
  12.      */  
  13.     public static boolean post(String path, Map<String, String> params, FormFile[] files) throws Exception{       
  14.         final String BOUNDARY = "---------------------------7da2137580612"//数据分隔线   
  15.         final String endline = "--" + BOUNDARY + "--\r\n";//数据结束标志   
  16.           
  17.         int fileDataLength = 0;  
  18.         for(FormFile uploadFile : files){//得到文件类型数据的总长度   
  19.             StringBuilder fileExplain = new StringBuilder();  
  20.             fileExplain.append("--");  
  21.             fileExplain.append(BOUNDARY);  
  22.             fileExplain.append("\r\n");  
  23.             fileExplain.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");  
  24.             fileExplain.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");  
  25.             fileExplain.append("\r\n");  
  26.             fileDataLength += fileExplain.length();  
  27.             if(uploadFile.getInStream()!=null){  
  28.                 fileDataLength += uploadFile.getFile().length();  
  29.             }else{  
  30.                 fileDataLength += uploadFile.getData().length;  
  31.             }  
  32.         }  
  33.         StringBuilder textEntity = new StringBuilder();  
  34.         for (Map.Entry<String, String> entry : params.entrySet()) {//构造文本类型参数的实体数据   
  35.             textEntity.append("--");  
  36.             textEntity.append(BOUNDARY);  
  37.             textEntity.append("\r\n");  
  38.             textEntity.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n");  
  39.             textEntity.append(entry.getValue());  
  40.             textEntity.append("\r\n");  
  41.         }  
  42.         //计算传输给服务器的实体数据总长度   
  43.         int dataLength = textEntity.toString().getBytes().length + fileDataLength +  endline.getBytes().length;  
  44.           
  45.         URL url = new URL(path);  
  46.         int port = url.getPort()==-1 ? 80 : url.getPort();  
  47.         Socket socket = new Socket(InetAddress.getByName(url.getHost()), port);          
  48.         OutputStream outStream = socket.getOutputStream();  
  49.         //下面完成HTTP请求头的发送   
  50.         String requestmethod = "POST "+ url.getPath()+" HTTP/1.1\r\n";  
  51.         outStream.write(requestmethod.getBytes());  
  52.         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";  
  53.         outStream.write(accept.getBytes());  
  54.         String language = "Accept-Language: zh-CN\r\n";  
  55.         outStream.write(language.getBytes());  
  56.         String contenttype = "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "\r\n";  
  57.         outStream.write(contenttype.getBytes());  
  58.         String contentlength = "Content-Length: "+ dataLength + "\r\n";  
  59.         outStream.write(contentlength.getBytes());  
  60.         String alive = "Connection: Keep-Alive\r\n";  
  61.         outStream.write(alive.getBytes());  
  62.         String host = "Host: "+ url.getHost() +":"+ port +"\r\n";  
  63.         outStream.write(host.getBytes());  
  64.         //写完HTTP请求头后根据HTTP协议再写一个回车换行   
  65.         outStream.write("\r\n".getBytes());  
  66.         //把所有文本类型的实体数据发送出来   
  67.         outStream.write(textEntity.toString().getBytes());           
  68.         //把所有文件类型的实体数据发送出来   
  69.         for(FormFile uploadFile : files){  
  70.             StringBuilder fileEntity = new StringBuilder();  
  71.             fileEntity.append("--");  
  72.             fileEntity.append(BOUNDARY);  
  73.             fileEntity.append("\r\n");  
  74.             fileEntity.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");  
  75.             fileEntity.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");  
  76.             outStream.write(fileEntity.toString().getBytes());  
  77.             if(uploadFile.getInStream()!=null){  
  78.                 byte[] buffer = new byte[1024];  
  79.                 int len = 0;  
  80.                 while((len = uploadFile.getInStream().read(buffer, 01024))!=-1){  
  81.                     outStream.write(buffer, 0, len);  
  82.                 }  
  83.                 uploadFile.getInStream().close();  
  84.             }else{  
  85.                 outStream.write(uploadFile.getData(), 0, uploadFile.getData().length);  
  86.             }  
  87.             outStream.write("\r\n".getBytes());  
  88.         }  
  89.         //下面发送数据结束标志,表示数据已经结束   
  90.         outStream.write(endline.getBytes());  
  91.           
  92.         BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));  
  93.         if(reader.readLine().indexOf("200")==-1){//读取web服务器返回的数据,判断请求码是否为200,如果不是200,代表请求失败   
  94.             return false;  
  95.         }  
  96.         outStream.flush();  
  97.         outStream.close();  
  98.         reader.close();  
  99.         socket.close();  
  100.         return true;  
  101.     }  
  102.       
  103.     /**  
  104.      * 提交数据到服务器  
  105.      * @param path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.xxx.cn或http://192.168.1.10:8080这样的路径测试)   
  106.      * @param params 请求参数 key为参数名,value为参数值  
  107.      * @param file 上传文件  
  108.      */  
  109.     public static boolean post(String path, Map<String, String> params, FormFile file) throws Exception{  
  110.        return post(path, params, new FormFile[]{file});  
  111.     }  

相关内容