ASP.NET中利用WebClient上传图片到远程服务的方法

时间:2022-02-06 22:24:20

一、客户端

1.页面

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

2.后台

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

二、服务端

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

以上所述是小编给大家介绍的ASP.NET中利用WebClient上传图片到远程服务的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:http://www.cnblogs.com/jinxin201211/archive/2017/01/13/6282096.html