通过 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 }

贴码结束!!!

转载于:https://www.cnblogs.com/liuyinjun/p/3980091.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值