一、客戶端
1.頁面
1 <form id="Form1" method="post" runat="server" enctype="multipart/form-data"> 2 <input id="MyFile" type="file" runat="server" /> 3 <br /> 4 <br /> 5 <asp:Button ID="Button1" runat="server" Text="上載文件" OnClick="Button1_Click"></asp:Button> 6 </form>
2.後台
1 System.Web.HttpFileCollection oFiles = System.Web.HttpContext.Current.Request.Files; 2 string FilePath = oFiles[0].FileName; 3 string FileName = FilePath.Substring(FilePath.LastIndexOf("\\") + 1); 4 byte[] b = new byte[oFiles[0].ContentLength]; 5 System.IO.Stream fs = (System.IO.Stream)oFiles[0].InputStream; 6 fs.Read(b, 0, oFiles[0].ContentLength); 7 string postData = "data=" + HttpUtility.UrlEncode(Convert.ToBase64String(b)); 8 var webclient = new WebClient(); 9 webclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); 10 byte[] byteArray = Encoding.UTF8.GetBytes(postData); 11 //byte[] buffer = webclient.UploadData("http://localhost/datapush/DataPush.ashx", "POST", byteArray);//ashx 12 byte[] buffer = webclient.UploadData("http://localhost/datapush/WebServiceDataPush.asmx/DataPush", "POST", byteArray);//asmx 13 var msg = Encoding.UTF8.GetString(buffer); 14 Response.Write(msg);
二、服務端
1 string msg = ""; 2 byte[] filedata = Convert.FromBase64String(context.Request["data"]); 3 if (filedata.Length == 0) 4 { 5 msg= "{\"code\":\"上傳的是空文件\"}"; 6 } 7 if (filedata.Length > 1048576) 8 { 9 msg = "{\"code\":\"圖片大小不能超過1M\"}"; 10 } 11 string fileextension = filedata[0].ToString() + filedata[1].ToString(); 12 if (fileextension == "7173") 13 { 14 fileextension = "gif"; 15 } 16 else if (fileextension == "255216") 17 { 18 fileextension = "jpg"; 19 } 20 else if (fileextension == "13780") 21 { 22 fileextension = "png"; 23 } 24 else if (fileextension == "6677") 25 { 26 fileextension = "bmp"; 27 } 28 else if (fileextension == "7373") 29 { 30 fileextension = "tif"; 31 } 32 else 33 { 34 msg = "{\"code\":\"上傳的文件不是圖片\"}"; 35 } 36 37 try 38 { 39 //保存圖片 40 string filename = Guid.NewGuid().ToString("D") + "." + fileextension; 41 System.IO.MemoryStream ms = new System.IO.MemoryStream(filedata); 42 System.IO.FileStream fs = new System.IO.FileStream(context.Server.MapPath("~/") + "/采集圖片/" + filename, System.IO.FileMode.Create); 43 ms.WriteTo(fs); 44 ms.Close(); 45 fs.Close(); 46 fs = null; 47 ms = null; 48 msg = "{\"code\":\"上傳圖片成功\"}"; 49 } 50 catch (Exception exe) 51 { 52 msg = "{\"code\":\"" + exe.Message + "\"}"; 53 } 54