This article mainly introduces the method of using WebClient to upload images to remote service in ASP, including the client and the service side, the code is annotated, the friend needs to refer to it.
First, the client
1. Page
<form id= "Form1" method= "POST" runat= "server" enctype= "Multipart/form-data" > <input id= "MyFile" type= "file" R unat= "Server"/> <br/> <br/> <asp:button id= "Button1" runat= "server" text= "Upload file" onclick= "but Ton1_click "></asp:Button> </form>
2. Backstage
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);
second, server
String msg = ""; byte[] Filedata = convert.frombase64string (context. request["Data"]); if (filedata. Length = = 0) {msg= "{\" code\ ": \" upload empty file \ "}"; } if (Filedata. Length > 1048576) {msg = "{\" code\ ": \" picture size cannot exceed 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\ ": \" The uploaded file is not a picture \ "}"; try {//Save picture 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 ("~/") + "/Capture picture/" + filename, System.IO.FileMode. Create); Ms. WriteTo (FS); Ms. Close (); Fs. Close (); FS = null; ms = NULL; msg = "{\" code\ ": \" upload picture success \ "}"; } catch (Exception exe) {msg = "{\" code\ ": \" + exe. Message + "\"} "; }
"Recommended"
1. asp free Video Tutorial
2. asp Tutorials
3. Eon the ASP Basic video tutorial