ASP.NET中利用WebClient上传图片到远程服务的方法 程序员文章站 2022-07-04 20:41:22 一、客户端 1.页面 一、客户端 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上传图片到远程服务的方法,希望对大家有所帮助 上一篇: vbs复制文件的脚本 下一篇: 你代替我请假吧 推荐阅读 ASP.NET中利用WebClient上传图片到远程服务的方法 WebClient上传图片到远程服务的代码示例 WebClient上传图片到远程服务的代码示例 ASP.NET中利用WebClient上传图片到远程服务的方法