Golang+Android文件上传(多文件上传、附带请求参数)

前端之家收集整理的这篇文章主要介绍了Golang+Android文件上传(多文件上传、附带请求参数)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

本文是上一篇文章Golang+Android(使用HttpURLConnection)实现文件上传升级版,实现多文件上传功能,并且附带http请求参数。

客户端代码

  1. /**
  2. * 使用HttpURLConnection通过POST方式提交请求,并上传文件
  3. *
  4. * @param actionUrl 访问的url
  5. * @param textParams 文本类型的POST参数(key:value)
  6. * @param filePaths 文件路径的集合
  7. * @return 服务器返回的数据,出现异常时返回 null
  8. */
  9. public static String postWithFiles(String actionUrl,Map<String,String> textParams,List<String> filePaths) {
  10. try {
  11. final String BOUNDARY = UUID.randomUUID().toString();
  12. final String PREFIX = "--";
  13. final String LINE_END = "\r\n";
  14.  
  15. final String MULTIPART_FROM_DATA = "multipart/form-data";
  16. final String CHARSET = "UTF-8";
  17.  
  18. URL uri = new URL(actionUrl);
  19. HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
  20.  
  21. //缓存大小
  22. conn.setChunkedStreamingMode(1024 * 64);
  23. //超时
  24. conn.setReadTimeout(5 * 1000);
  25. conn.setDoInput(true);
  26. conn.setDoOutput(true);
  27. conn.setUseCaches(false);
  28. conn.setRequestMethod("POST");
  29.  
  30. conn.setRequestProperty("connection","keep-alive");
  31. conn.setRequestProperty("Charset","UTF-8");
  32. conn.setRequestProperty("Content-Type",MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
  33.  
  34. // 拼接文本类型的参数
  35. StringBuilder textSb = new StringBuilder();
  36. if (textParams != null) {
  37. for (Map.Entry<String,String> entry : textParams.entrySet()) {
  38. textSb.append(PREFIX).append(BOUNDARY).append(LINE_END);
  39. textSb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINE_END);
  40. textSb.append("Content-Type: text/plain; charset=" + CHARSET + LINE_END);
  41. textSb.append("Content-Transfer-Encoding: 8bit" + LINE_END);
  42. textSb.append(LINE_END);
  43. textSb.append(entry.getValue());
  44. textSb.append(LINE_END);
  45. }
  46. }
  47.  
  48. DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
  49. outStream.write(textSb.toString().getBytes());
  50.  
  51. //参数POST方式
  52. //outStream.write("userId=1&cityId=26".getBytes());
  53.  
  54. // 发送文件数据
  55. if (filePaths != null) {
  56. for (String file : filePaths) {
  57. StringBuilder fileSb = new StringBuilder();
  58. fileSb.append(PREFIX).append(BOUNDARY).append(LINE_END);
  59. fileSb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" +
  60. file.substring(file.lastIndexOf("/") + 1) + "\"" + LINE_END);
  61. fileSb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
  62. fileSb.append(LINE_END);
  63. outStream.write(fileSb.toString().getBytes());
  64.  
  65. InputStream is = new FileInputStream(file);
  66. byte[] buffer = new byte[1024 * 8];
  67. int len;
  68. while ((len = is.read(buffer)) != -1) {
  69. outStream.write(buffer,len);
  70. }
  71.  
  72. is.close();
  73. outStream.write(LINE_END.getBytes());
  74. }
  75. }
  76.  
  77. // 请求结束标志
  78. outStream.write((PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes());
  79. outStream.flush();
  80.  
  81. // 得到响应码
  82. int responseCode = conn.getResponseCode();
  83. BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),CHARSET));
  84.  
  85. StringBuilder resultSb = null;
  86. String line;
  87. if (responseCode == 200) {
  88. resultSb = new StringBuilder();
  89. while ((line = br.readLine()) != null) {
  90. resultSb.append(line).append("\n");
  91. }
  92. }
  93.  
  94. br.close();
  95. outStream.close();
  96. conn.disconnect();
  97.  
  98. return resultSb == null ? null : resultSb.toString();
  99. } catch (IOException e) {
  100. e.printStackTrace();
  101. }
  102.  
  103. return null;
  104. }
服务器端代码
  1. //客户端上传多个文件,并带有请求参数
  2. func handleUploadFile(w http.ResponseWriter,r *http.Request) {
  3. fmt.Println("client:",r.RemoteAddr,"method:",r.Method)
  4.  
  5. r.ParseForm()
  6. r.ParseMultipartForm(32 << 20) //最大内存为32M
  7.  
  8. //读取参数
  9. userId := r.FormValue("userId")
  10. cityId := r.FormValue("cityId")
  11. log.Println("userId=",userId,"cityId=",cityId)
  12.  
  13. mp := r.MultipartForm
  14. if mp == nil {
  15. log.Println("not MultipartForm.")
  16. w.Write(([]byte)("不是MultipartForm格式"))
  17. return
  18. }
  19.  
  20. fileHeaders,findFile := mp.File["file"]
  21. if !findFile || len(fileHeaders) == 0 {
  22. log.Println("file count == 0.")
  23. w.Write(([]byte)("没有上传文件"))
  24. return
  25. }
  26.  
  27. for _,v := range fileHeaders {
  28. fileName := v.Filename
  29. file,err := v.Open()
  30. checkErrorV2(err,"Open file error."+fileName)
  31. defer file.Close()
  32.  
  33. outputFilePath := "/home/admin/桌面/" + fileName
  34. writer,err := os.OpenFile(outputFilePath,os.O_WRONLY|os.O_CREATE,0666)
  35. checkErrorV2(err,"Open local file error")
  36. io.Copy(writer,file)
  37. }
  38.  
  39. msg := fmt.Sprintf("成功上传了%d个文件",len(fileHeaders))
  40. w.Write(([]byte)(msg))
  41. }
注:checkErrorV2是一个简单的检查错误函数

猜你在找的Go相关文章