您好,登錄后才能下訂單哦!
本篇文章展示了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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。