您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
本篇文章展示了ASP.NET中WebClient上传图片到远程服务的方法,代码简明扼要容易理解,如果在日常工作遇到这个疑问。希望大家通过这篇文章,找到解决疑问的办法。
一、客户端
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 + "\"}"; }
看完上述内容,你们掌握WebClient上传图片到远程服务的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。