Android 本地文件上传到服务器

左手的ㄟ右手 2022-04-04 11:38 732阅读 0赞
  1. /**
  2. * fileName 文件名(不带后缀)
  3. * filePath 文件的本地路径 (xxx / xx / test.jpg)
  4. */
  5. public static void uploadFile(String strServerUrl, String strFile) {
  6. String end = "\r\n";
  7. String twoHyphens = "--";
  8. String boundary = "*****";
  9. try {
  10. URL url = new URL(strServerUrl);
  11. HttpURLConnection con = (HttpURLConnection) url.openConnection();
  12. /* 允许Input、Output,不使用Cache */
  13. con.setDoInput(true);
  14. con.setDoOutput(true);
  15. con.setUseCaches(false);
  16. /* 设置传送的method=POST */
  17. con.setRequestMethod("POST");
  18. /* setRequestProperty */
  19. con.setRequestProperty("Connection", "Keep-Alive");
  20. con.setRequestProperty("Charset", "UTF-8");
  21. con.setRequestProperty("Content-Type",
  22. "multipart/form-data;boundary=" + boundary);
  23. String strFileName = strFile.substring(strFile.lastIndexOf("/") + 1);
  24. /* 设置DataOutputStream */
  25. DataOutputStream ds =
  26. new DataOutputStream(con.getOutputStream());
  27. ds.writeBytes(twoHyphens + boundary + end);
  28. ds.writeBytes("Content-Disposition: form-data; " +
  29. "name=\"file1\";filename=\"" +
  30. strFileName + "\"" + end);
  31. ds.writeBytes(end);
  32. /* 取得文件的FileInputStream */
  33. FileInputStream fStream = new FileInputStream(strFile);
  34. /* 设置每次写入1024bytes */
  35. int bufferSize = 10240;
  36. byte[] buffer = new byte[bufferSize];
  37. int length = -1;
  38. /* 从文件读取数据至缓冲区 */
  39. while ((length = fStream.read(buffer)) != -1) {
  40. /* 将资料写入DataOutputStream中 */
  41. ds.write(buffer, 0, length);
  42. }
  43. ds.writeBytes(end);
  44. ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
  45. /* close streams */
  46. fStream.close();
  47. ds.flush();
  48. /* 取得Response内容 */
  49. InputStream is = con.getInputStream();
  50. int ch;
  51. StringBuffer b = new StringBuffer();
  52. while ((ch = is.read()) != -1) {
  53. b.append((char) ch);
  54. }
  55. /* 关闭DataOutputStream */
  56. ds.close();
  57. is.close();
  58. } catch (Exception e) {
  59. e.printStackTrace();
  60. }
  61. }

发表评论

表情:
评论列表 (有 0 条评论,732人围观)

还没有评论,来说两句吧...

相关阅读