客户端一:下面为 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 /** 2 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse 3 * response) 4 */ 5 @SuppressWarnings("unchecked") 6 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 7 // TODO Auto-generated method stub 8 PrintWriter out = response.getWriter(); 9 try { 10 // String userName = request.getParameter("userName");//获取form 11 // System.out.println(userName); 12 List<FileItem> items = this.upload.parseRequest(request); 13 if (items != null && !items.isEmpty()) { 14 for (FileItem fileItem : items) { 15 String filename = fileItem.getName(); 16 if (filename == null) {// 说明获取到的可能为表单数据,为表单数据时要自己读取 17 InputStream formInputStream = fileItem.getInputStream(); 18 BufferedReader formBr = new BufferedReader(new InputStreamReader(formInputStream)); 19 StringBuffer sb = new StringBuffer(); 20 String line = null; 21 while ((line = formBr.readLine()) != null) { 22 sb.append(line); 23 } 24 String userName = sb.toString(); 25 System.out.println("姓名为:" + userName); 26 continue; 27 } 28 String filepath = filedir + File.separator + filename; 29 System.out.println("文件保存路径为:" + filepath); 30 File file = new File(filepath); 31 InputStream inputSteam = fileItem.getInputStream(); 32 BufferedInputStream fis = new BufferedInputStream(inputSteam); 33 FileOutputStream fos = new FileOutputStream(file); 34 int f; 35 while ((f = fis.read()) != -1) { 36 fos.write(f); 37 } 38 fos.flush(); 39 fos.close(); 40 fis.close(); 41 inputSteam.close(); 42 System.out.println("文件:" + filename + "上传成功!"); 43 } 44 } 45 System.out.println("上传文件成功!"); 46 out.write("上传文件成功!"); 47 } catch (FileUploadException e) { 48 e.printStackTrace(); 49 out.write("上传文件失败:" + e.getMessage()); 50 } 51 }
客户端二:下面为用 .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 }
贴码结束!!!
时间: 2024-10-25 11:51:20