Using WebClient in ASP. NET to upload images to remote services,
I. Client
1. Page
<Form id = "Form1" method = "post" runat = "server" enctype = "multipart/form-data"> <input id = "MyFile" type = "file" runat = "server"/> <br/> <asp: button ID = "Button1" runat = "server" Text = "Upload File" OnClick = "button#click"> </asp: Button> </form>
2. Background
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);
Ii. Server
String msg = ""; byte [] filedata = Convert. fromBase64String (context. request ["data"]); if (filedata. length = 0) {msg = "{\" code \ ": \" empty file \ "}";} if (filedata. length> 1048576) {msg = "{\" code \ ": \" the image size cannot exceed 1 MB \ "}";} string fileextension = filedata [0]. toString () + filedata [1]. toString (); if (fileextension = "7173") {fileextension = "gif";} else if (fileextension = "255216") {fileextension = "j Pg ";} else if (fileextension =" 13780 ") {fileextension =" png ";} else if (fileextension =" 6677 ") {fileextension =" bmp ";} else if (fileextension = "7373") {fileextension = "tif";} else {msg = "{\" code \": \ "the uploaded file is not an image \"} ";} try {// Save the image string filename = Guid. newGuid (). toString ("D") + ". "+ fileextension; System. IO. memoryStream MS = new System. IO. memoryStream (filedata); System. IO. fileStr Eam fs = new System. IO. FileStream (context. Server. MapPath ("~ /") +"/Capture image/"+ filename, System. IO. fileMode. create); ms. writeTo (fs); ms. close (); fs. close (); fs = null; MS = null; msg = "{\" code \ ": \" uploaded image \ "}";} catch (Exception exe) {msg = "{\" code \ ": \" "+ exe. message + "\"}";}
The above is a small series of ASP. NET using WebClient to upload images to the remote service method, I hope to help you, if you have any questions, please leave a message, xiaobian will reply to you in a timely manner. Thank you very much for your support for the help House website!