单文件上传UpLoadFile.java 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package com.ics.aop.tool;
  2. import java.io.DataOutputStream;
  3. import java.io.FileInputStream;
  4. import java.io.InputStream;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. /**
  8. * 文件上传的工具类
  9. *
  10. */
  11. public class UpLoadFile {
  12. private static final int TIMEOUT = 10000;// 10秒
  13. public static String sendFile(String urlPath, String filePath,
  14. String newName) throws Exception {
  15. String end = "\r\n";
  16. String twoHyphens = "--";
  17. String boundary = "*****";
  18. URL url = new URL(urlPath);
  19. HttpURLConnection con = (HttpURLConnection) url.openConnection();
  20. /* 允许Input、Output,不使用Cache */
  21. con.setDoInput(true);
  22. con.setDoOutput(true);
  23. con.setUseCaches(false);
  24. /* 设置传送的method=POST */
  25. con.setRequestMethod("POST");
  26. /* setRequestProperty */
  27. con.setRequestProperty("Connection", "Keep-Alive");
  28. con.setRequestProperty("Charset", "UTF-8");
  29. con.setRequestProperty("Content-Type", "multipart/form-data;boundary="
  30. + boundary);
  31. /* 设置DataOutputStream */
  32. DataOutputStream ds = new DataOutputStream(con.getOutputStream());
  33. ds.writeBytes(twoHyphens + boundary + end);
  34. ds.writeBytes("Content-Disposition: form-data; "
  35. + "name=\"file1\";filename=\"" + newName + "\"" + end);
  36. ds.writeBytes(end);
  37. /* 取得文件的FileInputStream */
  38. FileInputStream fStream = new FileInputStream(filePath);
  39. /* 设置每次写入1024bytes */
  40. int bufferSize = 1024;
  41. byte[] buffer = new byte[bufferSize];
  42. int length = -1;
  43. /* 从文件读取数据至缓冲区 */
  44. while ((length = fStream.read(buffer)) != -1) {
  45. /* 将资料写入DataOutputStream中 */
  46. ds.write(buffer, 0, length);
  47. }
  48. ds.writeBytes(end);
  49. ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
  50. /* close streams */
  51. fStream.close();
  52. ds.flush();
  53. /* 取得Response内容 */
  54. InputStream is = con.getInputStream();
  55. int ch;
  56. StringBuffer b = new StringBuffer();
  57. while ((ch = is.read()) != -1) {
  58. b.append((char) ch);
  59. }
  60. /* 关闭DataOutputStream */
  61. ds.close();
  62. return b.toString();
  63. }
  64. }