Document

[asp.net] 利用WebClient上传图片到远程服务

一、客户端

1.页面

  1.   <form id="Form1" method="post" runat="server" enctype="multipart/form-data">
  2.     <input id="MyFile" type="file" runat="server" />
  3.     <br />
  4.     <br />
  5.     <asp:Button ID="Button1" runat="server" Text="上载文件" OnClick="Button1_Click"></asp:Button>
  6.   </form>

2.后台

  1. System.Web.HttpFileCollection oFiles = System.Web.HttpContext.Current.Request.Files;
  2. ].FileName;
  3. );
  4. ].ContentLength];
  5. System.IO.Stream fs = (System.IO.Stream)oFiles[].InputStream;
  6. fs.Read(b, , oFiles[].ContentLength);
  7. string postData = "data=" + HttpUtility.UrlEncode(Convert.ToBase64String(b));
  8. var webclient = new WebClient();
  9. webclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
  10. byte[] byteArray = Encoding.UTF8.GetBytes(postData);
  11. //byte[] buffer = webclient.UploadData("http://localhost/datapush/DataPush.ashx", "POST", byteArray);//ashx
  12. byte[] buffer = webclient.UploadData("http://localhost/datapush/WebServiceDataPush.asmx/DataPush", "POST", byteArray);//asmx
  13. var msg = Encoding.UTF8.GetString(buffer);
  14. Response.Write(msg);

二、服务端

  1. string msg = "";
  2. byte[] filedata = Convert.FromBase64String(context.Request["data"]);
  3. )
  4. {
  5. msg= "{\"code\":\"上传的是空文件\"}";
  6. }
  7. )
  8. {
  9. msg = "{\"code\":\"图片大小不能超过1M\"}";
  10. }
  11. ].ToString() + filedata[].ToString();
  12. ")
  13. {
  14. fileextension = "gif";
  15. }
  16. ")
  17. {
  18. fileextension = "jpg";
  19. }
  20. ")
  21. {
  22. fileextension = "png";
  23. }
  24. ")
  25. {
  26. fileextension = "bmp";
  27. }
  28. ")
  29. {
  30. fileextension = "tif";
  31. }
  32. else
  33. {
  34. msg = "{\"code\":\"上传的文件不是图片\"}";
  35. }
  36.  
  37. try
  38. {
  39. //保存图片
  40. string filename = Guid.NewGuid().ToString("D") + "." + fileextension;
  41. System.IO.MemoryStream ms = new System.IO.MemoryStream(filedata);
  42. System.IO.FileStream fs = new System.IO.FileStream(context.Server.MapPath("~/") + "/采集图片/" + filename, System.IO.FileMode.Create);
  43. ms.WriteTo(fs);
  44. ms.Close();
  45. fs.Close();
  46. fs = null;
  47. ms = null;
  48. msg = "{\"code\":\"上传图片成功\"}";
  49. }
  50. catch (Exception exe)
  51. {
  52. msg = "{\"code\":\"" + exe.Message + "\"}";
  53. }

 

posted @ 2019-04-16 11:21  从未被超越  阅读(826)  评论(0编辑  收藏  举报