当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET中利用WebClient上传图片到远程服务的方法

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

十八届中央候补委员名单,户外资料网,徐工集团总部在哪里

一、客户端

1.页面

<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.后台

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);

二、服务端

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上传图片到远程服务的方法,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网