歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android使用http協議實現文件的上傳

Android使用http協議實現文件的上傳

日期:2017/3/1 11:12:42   编辑:Linux編程

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. public class FormFile {
  9. /* 上傳文件的數據 */
  10. private byte[] data;
  11. private InputStream inStream;
  12. private File file;
  13. /* 文件名稱 */
  14. private String filname;
  15. /* 請求參數名稱*/
  16. private String parameterName;
  17. /* 內容類型 */
  18. private String contentType = "application/octet-stream";
  19. /**
  20. *
  21. * @param filname 文件名稱
  22. * @param data 上傳的文件數據
  23. * @param parameterName 參數
  24. * @param contentType 內容類型
  25. */
  26. public FormFile(String filname, byte[] data, String parameterName, String contentType) {
  27. this.data = data;
  28. this.filname = filname;
  29. this.parameterName = parameterName;
  30. if(contentType!=null) this.contentType = contentType;
  31. }
  32. /**
  33. *
  34. * @param filname 文件名
  35. * @param file 上傳的文件
  36. * @param parameterName 參數
  37. * @param contentType 內容內容類型
  38. */
  39. public FormFile(String filname, File file, String parameterName, String contentType) {
  40. this.filname = filname;
  41. this.parameterName = parameterName;
  42. this.file = file;
  43. try {
  44. this.inStream = new FileInputStream(file);
  45. } catch (FileNotFoundException e) {
  46. e.printStackTrace();
  47. }
  48. if(contentType!=null) this.contentType = contentType;
  49. }
  50. public File getFile() {
  51. return file;
  52. }
  53. public InputStream getInStream() {
  54. return inStream;
  55. }
  56. public byte[] getData() {
  57. return data;
  58. }
  59. public String getFilname() {
  60. return filname;
  61. }
  62. public void setFilname(String filname) {
  63. this.filname = filname;
  64. }
  65. public String getParameterName() {
  66. return parameterName;
  67. }
  68. public void setParameterName(String parameterName) {
  69. this.parameterName = parameterName;
  70. }
  71. public String getContentType() {
  72. return contentType;
  73. }
  74. public void setContentType(String contentType) {
  75. this.contentType = contentType;
  76. }
  77. }
下面的方法封裝的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. int fileDataLength = 0;
  17. for(FormFile uploadFile : files){//得到文件類型數據的總長度
  18. StringBuilder fileExplain = new StringBuilder();
  19. fileExplain.append("--");
  20. fileExplain.append(BOUNDARY);
  21. fileExplain.append("\r\n");
  22. fileExplain.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
  23. fileExplain.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");
  24. fileExplain.append("\r\n");
  25. fileDataLength += fileExplain.length();
  26. if(uploadFile.getInStream()!=null){
  27. fileDataLength += uploadFile.getFile().length();
  28. }else{
  29. fileDataLength += uploadFile.getData().length;
  30. }
  31. }
  32. StringBuilder textEntity = new StringBuilder();
  33. for (Map.Entry<String, String> entry : params.entrySet()) {//構造文本類型參數的實體數據
  34. textEntity.append("--");
  35. textEntity.append(BOUNDARY);
  36. textEntity.append("\r\n");
  37. textEntity.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n");
  38. textEntity.append(entry.getValue());
  39. textEntity.append("\r\n");
  40. }
  41. //計算傳輸給服務器的實體數據總長度
  42. int dataLength = textEntity.toString().getBytes().length + fileDataLength + endline.getBytes().length;
  43. URL url = new URL(path);
  44. int port = url.getPort()==-1 ? 80 : url.getPort();
  45. Socket socket = new Socket(InetAddress.getByName(url.getHost()), port);
  46. OutputStream outStream = socket.getOutputStream();
  47. //下面完成HTTP請求頭的發送
  48. String requestmethod = "POST "+ url.getPath()+" HTTP/1.1\r\n";
  49. outStream.write(requestmethod.getBytes());
  50. 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";
  51. outStream.write(accept.getBytes());
  52. String language = "Accept-Language: zh-CN\r\n";
  53. outStream.write(language.getBytes());
  54. String contenttype = "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "\r\n";
  55. outStream.write(contenttype.getBytes());
  56. String contentlength = "Content-Length: "+ dataLength + "\r\n";
  57. outStream.write(contentlength.getBytes());
  58. String alive = "Connection: Keep-Alive\r\n";
  59. outStream.write(alive.getBytes());
  60. String host = "Host: "+ url.getHost() +":"+ port +"\r\n";
  61. outStream.write(host.getBytes());
  62. //寫完HTTP請求頭後根據HTTP協議再寫一個回車換行
  63. outStream.write("\r\n".getBytes());
  64. //把所有文本類型的實體數據發送出來
  65. outStream.write(textEntity.toString().getBytes());
  66. //把所有文件類型的實體數據發送出來
  67. for(FormFile uploadFile : files){
  68. StringBuilder fileEntity = new StringBuilder();
  69. fileEntity.append("--");
  70. fileEntity.append(BOUNDARY);
  71. fileEntity.append("\r\n");
  72. fileEntity.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
  73. fileEntity.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");
  74. outStream.write(fileEntity.toString().getBytes());
  75. if(uploadFile.getInStream()!=null){
  76. byte[] buffer = new byte[1024];
  77. int len = 0;
  78. while((len = uploadFile.getInStream().read(buffer, 0, 1024))!=-1){
  79. outStream.write(buffer, 0, len);
  80. }
  81. uploadFile.getInStream().close();
  82. }else{
  83. outStream.write(uploadFile.getData(), 0, uploadFile.getData().length);
  84. }
  85. outStream.write("\r\n".getBytes());
  86. }
  87. //下面發送數據結束標志,表示數據已經結束
  88. outStream.write(endline.getBytes());
  89. BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  90. if(reader.readLine().indexOf("200")==-1){//讀取web服務器返回的數據,判斷請求碼是否為200,如果不是200,代表請求失敗
  91. return false;
  92. }
  93. outStream.flush();
  94. outStream.close();
  95. reader.close();
  96. socket.close();
  97. return true;
  98. }
  99. /**
  100. * 提交數據到服務器
  101. * @param path 上傳路徑(注:避免使用localhost或127.0.0.1這樣的路徑測試,因為它會指向手機模擬器,你可以使用http://www.xxx.cn或http://192.168.1.10:8080這樣的路徑測試)
  102. * @param params 請求參數 key為參數名,value為參數值
  103. * @param file 上傳文件
  104. */
  105. public static boolean post(String path, Map<String, String> params, FormFile file) throws Exception{
  106. return post(path, params, new FormFile[]{file});
  107. }
Copyright © Linux教程網 All Rights Reserved