通過 http post 方式上傳多張圖片


客戶端一:下面為 Android 客戶端的實現代碼:

  1 /**
  2   * android上傳文件到服務器
  3   * 
  4   * 下面為 http post 報文格式
  5   * 
  6  POST/logsys/home/uploadIspeedLog!doDefault.html HTTP/1.1 
  7    Accept: text/plain, 
  8    Accept-Language: zh-cn 
  9    Host: 192.168.24.56
 10    Content-Type:multipart/form-data;boundary=-----------------------------7db372eb000e2
 11    User-Agent: WinHttpClient 
 12    Content-Length: 3693
 13    Connection: Keep-Alive   注:上面為報文頭
 14    -------------------------------7db372eb000e2
 15    Content-Disposition: form-data; name="file"; filename="kn.jpg"
 16    Content-Type: image/jpeg
 17    (此處省略jpeg文件二進制數據...)
 18    -------------------------------7db372eb000e2--
 19   * 
 20   * @param picPaths
 21   *            需要上傳的文件路徑集合
 22   * @param requestURL
 23   *            請求的url
 24   * @return 返回響應的內容
 25   */
 26  public static String uploadFile(String[] picPaths, String requestURL) {
 27   String boundary = UUID.randomUUID().toString(); // 邊界標識 隨機生成
 28   String prefix = "--", end = "\r\n";
 29   String content_type = "multipart/form-data"; // 內容類型
 30   String CHARSET = "utf-8"; // 設置編碼
 31   int TIME_OUT = 10 * 10000000; // 超時時間
 32   try {
 33    URL url = new URL(requestURL);
 34    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 35    conn.setReadTimeout(TIME_OUT);
 36    conn.setConnectTimeout(TIME_OUT);
 37    conn.setDoInput(true); // 允許輸入流
 38    conn.setDoOutput(true); // 允許輸出流
 39    conn.setUseCaches(false); // 不允許使用緩存
 40    conn.setRequestMethod("POST"); // 請求方式
 41    conn.setRequestProperty("Charset", "utf-8"); // 設置編碼
 42    conn.setRequestProperty("connection", "keep-alive");
 43    conn.setRequestProperty("Content-Type", content_type + ";boundary=" + boundary);
 44    /**
 45     * 當文件不為空,把文件包裝並且上傳
 46     */
 47    OutputStream outputSteam = conn.getOutputStream();
 48    DataOutputStream dos = new DataOutputStream(outputSteam);
 49     
 50    StringBuffer stringBuffer = new StringBuffer();
 51    stringBuffer.append(prefix);
 52    stringBuffer.append(boundary);
 53    stringBuffer.append(end);
 54    dos.write(stringBuffer.toString().getBytes());
 55     
 56    String name = "userName";
 57    dos.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"" + end);
 58    dos.writeBytes(end);
 59    dos.writeBytes("zhangSan");
 60    dos.writeBytes(end);
 61  
 62     
 63    for(int i = 0; i < picPaths.length; i++){
 64    File file = new File(picPaths[i]);
 65     
 66    StringBuffer sb = new StringBuffer();
 67    sb.append(prefix);
 68    sb.append(boundary);
 69    sb.append(end);
 70    
 71    /**
 72     * 這里重點注意: name里面的值為服務器端需要key 只有這個key 才可以得到對應的文件
 73     * filename是文件的名字,包含后綴名的 比如:abc.png
 74     */
 75    sb.append("Content-Disposition: form-data; name=\"" + i + "\"; filename=\"" + file.getName() + "\"" + end);
 76    sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + end);
 77    sb.append(end);
 78    dos.write(sb.toString().getBytes());
 79    
 80    InputStream is = new FileInputStream(file);
 81    byte[] bytes = new byte[8192];//8k
 82    int len = 0;
 83    while ((len = is.read(bytes)) != -1) {
 84     dos.write(bytes, 0, len);
 85    }
 86    is.close();
 87    dos.write(end.getBytes());//一個文件結束標志
 88   }
 89    byte[] end_data = (prefix + boundary + prefix + end).getBytes();//結束 http 流 
 90    dos.write(end_data);
 91    dos.flush();
 92    /**
 93     * 獲取響應碼 200=成功 當響應成功,獲取響應的流
 94     */
 95    int res = conn.getResponseCode();
 96    Log.e("TAG", "response code:" + res);
 97    if (res == 200) {
 98     return SUCCESS;
 99    }
100   } catch (MalformedURLException e) {
101    e.printStackTrace();
102   } catch (IOException e) {
103    e.printStackTrace();
104   }
105   return FAILURE;
106  }

服務端一:下面為 Java Web 服務端 servlet 的實現代碼:

 1 public class FileImageUploadServlet extends HttpServlet {
 2     private static final long serialVersionUID = 1L;
 3     private ServletFileUpload upload;
 4     private final long MAXSize = 4194304 * 2L;// 4*2MB
 5     private String filedir = null;
 6 
 7     /**
 8      * @see HttpServlet#HttpServlet()
 9      */
10     public FileImageUploadServlet() {
11         super();
12         // TODO Auto-generated constructor stub
13     }
14 
15     /**
16      * 設置文件上傳的初始化信息
17      * 
18      * @see Servlet#init(ServletConfig)
19      */
20     public void init(ServletConfig config) throws ServletException {
21         FileItemFactory factory = new DiskFileItemFactory();// Create a factory
22                                                             // for disk-based
23                                                             // file items
24         this.upload = new ServletFileUpload(factory);// Create a new file upload
25                                                         // handler
26         this.upload.setSizeMax(this.MAXSize);// Set overall request size
27                                                 // constraint 4194304
28         filedir = config.getServletContext().getRealPath("images");
29         System.out.println("filedir=" + filedir);
30     }
31 
32     /**
33      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
34      *      response)
35      */
36     @SuppressWarnings("unchecked")
37     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
38         // TODO Auto-generated method stub
39         PrintWriter out = response.getWriter();
40         try {
41             // String userName = request.getParameter("userName");//獲取form
42             // System.out.println(userName);
43 
44             List<FileItem> items = this.upload.parseRequest(request);
45             if (items != null && !items.isEmpty()) {
46                 for (FileItem fileItem : items) {
47                     String filename = fileItem.getName();
48                     if (filename == null) {// 說明獲取到的可能為表單數據,為表單數據時要自己讀取
49                         InputStream formInputStream = fileItem.getInputStream();
50                         BufferedReader formBr = new BufferedReader(new InputStreamReader(formInputStream));
51                         StringBuffer sb = new StringBuffer();
52                         String line = null;
53                         while ((line = formBr.readLine()) != null) {
54                             sb.append(line);
55                         }
56                         String userName = sb.toString();
57                         System.out.println("姓名為:" + userName);
58                         continue;
59                     }
60                     String filepath = filedir + File.separator + filename;
61                     System.out.println("文件保存路徑為:" + filepath);
62                     File file = new File(filepath);
63                     InputStream inputSteam = fileItem.getInputStream();
64                     BufferedInputStream fis = new BufferedInputStream(inputSteam);
65                     FileOutputStream fos = new FileOutputStream(file);
66                     int f;
67                     while ((f = fis.read()) != -1) {
68                         fos.write(f);
69                     }
70                     fos.flush();
71                     fos.close();
72                     fis.close();
73                     inputSteam.close();
74                     System.out.println("文件:" + filename + "上傳成功!");
75                 }
76             }
77             System.out.println("上傳文件成功!");
78             out.write("上傳文件成功!");
79         } catch (FileUploadException e) {
80             e.printStackTrace();
81             out.write("上傳文件失敗:" + e.getMessage());
82         }
83     }
84 
85 }

 

客戶端二:下面為用 .NET 作為客戶端實現的 C# 代碼:

 1 /** 下面為 http post 報文格式
 2      POST/logsys/home/uploadIspeedLog!doDefault.html HTTP/1.1 
 3    Accept: text/plain, 
 4    Accept-Language: zh-cn 
 5    Host: 192.168.24.56
 6    Content-Type:multipart/form-data;boundary=-----------------------------7db372eb000e2
 7    User-Agent: WinHttpClient 
 8    Content-Length: 3693
 9    Connection: Keep-Alive   注:上面為報文頭
10    -------------------------------7db372eb000e2
11    Content-Disposition: form-data; name="file"; filename="kn.jpg"
12    Content-Type: image/jpeg
13    (此處省略jpeg文件二進制數據...)
14    -------------------------------7db372eb000e2--
15          * 
16          * */
17         private STATUS uploadImages(String uri)
18         {
19             String boundary = "------------Ij5ei4ae0ei4cH2ae0Ef1ei4Ij5gL6";; // 邊界標識
20       String prefix = "--", end = "\r\n";
21             /** 根據uri創建WebRequest對象**/
22             WebRequest httpReq = WebRequest.Create(new Uri(uri));
23             httpReq.Method = "POST";//方法名   
24             httpReq.Timeout = 10 * 10000000;//超時時間
25             httpReq.ContentType = "multipart/form-data; boundary=" + boundary;//數據類型
26             /*******************************/
27   try {
28             /** 第一個數據為form,名稱為par,值為123 */
29    StringBuilder stringBuilder = new StringBuilder();
30             stringBuilder.Append(prefix);
31             stringBuilder.Append(boundary);
32             stringBuilder.Append(end);
33    String name = "userName";
34             stringBuilder.Append("Content-Disposition: form-data; name=\"" + name + "\"" + end);
35             stringBuilder.Append(end);
36             stringBuilder.Append("zhangSan");
37             stringBuilder.Append(end);
38             /*******************************/
39             Stream steam = httpReq.GetRequestStream();//獲取到請求流
40             byte[] byte8 = Encoding.UTF8.GetBytes(stringBuilder.ToString());//把form的數據以二進制流的形式寫入
41             steam.Write(byte8, 0, byte8.Length);
42  
43             /** 列出 G:/images/ 文件夾下的所有文件**/
44    DirectoryInfo fileFolder = new DirectoryInfo("G:/images/");
45             FileSystemInfo[] files = fileFolder.GetFileSystemInfos();
46             for(int   i = 0;   i < files.Length; i++) 
47         { 
48         FileInfo   file   =   files[i]   as   FileInfo;
49               stringBuilder.Clear();//清理
50               stringBuilder.Append(prefix);
51               stringBuilder.Append(boundary);
52               stringBuilder.Append(end);
53               /**
54               * 這里重點注意: name里面的值為服務器端需要key 只有這個key 才可以得到對應的文件
55               * filename是文件的名字,包含后綴名的 比如:abc.png
56               */
57               stringBuilder.Append("Content-Disposition: form-data; name=\"" + i + "\"; filename=\"" + file.Name + "\"" + end);
58               stringBuilder.Append("Content-Type: application/octet-stream; charset=utf-8" + end);
59               stringBuilder.Append(end);
60               byte[] byte2 = Encoding.UTF8.GetBytes(stringBuilder.ToString());
61               steam.Write(byte2, 0, byte2.Length);
62               FileStream fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);//讀入一個文件。
63               BinaryReader r = new BinaryReader(fs);//將讀入的文件保存為二進制文件。
64               int bufferLength = 8192;//每次上傳8k;
65               byte[] buffer = new byte[bufferLength];
66               long offset = 0;//已上傳的字節數
67               int size = r.Read(buffer, 0, bufferLength);
68               while (size > 0)
69               {
70                   steam.Write(buffer, 0, size);
71                   offset += size;
72                   size = r.Read(buffer, 0, bufferLength);
73               }
74               /** 每個文件結束后有換行 **/
75               byte[] byteFileEnd = Encoding.UTF8.GetBytes(end);
76               steam.Write(byteFileEnd, 0, byteFileEnd.Length);
77               fs.Close();
78               r.Close();
79             }
80             byte[] byte1 = Encoding.UTF8.GetBytes(prefix + boundary + prefix + end);//文件結束標志
81             steam.Write(byte1, 0, byte1.Length);
82             steam.Close();
83             WebResponse response = httpReq.GetResponse();// 獲取響應
84             Console.WriteLine(((HttpWebResponse)response).StatusDescription);// 顯示狀態
85             steam = response.GetResponseStream();//獲取從服務器返回的流
86             StreamReader reader = new StreamReader(steam);
87             string responseFromServer = reader.ReadToEnd();//讀取內容
88             Console.WriteLine(responseFromServer);
89             // 清理流
90             reader.Close();
91             steam.Close();
92             response.Close();
93             return STATUS.SUCCESS;
94   } catch (System.Exception e) {
95             Console.WriteLine(e.ToString());
96             return STATUS.FAILURE;
97   } 
98 }

服務端二: 下面為 .NET 實現的服務端 C# 代碼:

1 protected void Page_Load(object sender, EventArgs e)
2 {
3    string userName = Request.Form["userName"];//接收form
4    HttpFileCollection MyFilecollection = Request.Files;//接收文件
5    for (int i = 0; i < MyFilecollection.Count; i++ )
6    {
7       MyFilecollection[i].SaveAs(Server.MapPath("~/netUploadImages/" + MyFilecollection[i].FileName));//保存圖片
8    }
9 }

貼碼結束!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM