一、客户端
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;
- ].FileName;
- );
- ].ContentLength];
- System.IO.Stream fs = (System.IO.Stream)oFiles[].InputStream;
- fs.Read(b, , oFiles[].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"]);
- )
- {
- msg= "{"code":"上传的是空文件"}";
- }
- )
- {
- msg = "{"code":"图片大小不能超过1M"}";
- }
- ].ToString() + filedata[].ToString();
- ")
- {
- fileextension = "gif";
- }
- ")
- {
- fileextension = "jpg";
- }
- ")
- {
- fileextension = "png";
- }
- ")
- {
- fileextension = "bmp";
- }
- ")
- {
- 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 + ""}";
- }