通过HtppWebRequest发送图片到服务器并保存
之前写的楼主没有测试,后来发现用起来有点小问题 就修改了一下,现在已经亲测可用 完全没有问题了 下面就开始贴代码了
首先将图片装换成功byte 数组
这个path是图片的路径 例如d:12.png;
public byte[] SaveImage(string path) { FileStream fs=new FileStream(path,FileMode.Open,FileAccess.Read); BinaryReader br=new BinaryReader(fs); byte[] imgBytes = br.ReadBytes((int) fs.Length); return imgBytes; }
然后上传图片流
这里要注意点 写入请求流的strean 用完要关闭
/// <summary> /// 上传图片流 /// </summary> /// <param name="data"></param> private bool ImageRequest(byte[] data) { const string host = "http://www.baidu.com"; const string path = "/ImageManagerApi/GetImageByte"; string url = host + path; HttpWebResponse httpResponse = null; HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url); httpRequest.Method = "POST"; httpRequest.Headers.Add("FileSize", data.Length.ToString()); using (Stream stream = httpRequest.GetRequestStream()) { stream.Write(data, 0, data.Length); stream.Close(); } try { httpResponse = (HttpWebResponse)httpRequest.GetResponse(); } catch (WebException ex) { httpResponse = (HttpWebResponse)ex.Response; } //响应流 Stream st = httpResponse.GetResponseStream(); StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8")); string result = reader.ReadToEnd(); if ("ok".Contains(result)) return true; return false; }
服务器接收的方法
/// <summary> /// 获取图片流 /// 保存图片 /// </summary> public void GetImageByte() { try { int fileSize = int.Parse(Request.Headers["FileSize"].ToString()); byte[] data = Request.BinaryRead(fileSize); DebugHelper.Info(BitConverter.ToString(data)); var path = "/Upload/LINGDAO/" + DateTime.Now.Date.ToString("yyyy-MM-dd") + "/"; var serverPath = Server.MapPath("~" + path); if (!Directory.Exists(serverPath)) { Directory.CreateDirectory(serverPath); } string fileName = Guid.NewGuid().ToString(); //图片存储到流中 MemoryStream ms = new MemoryStream(data); Image image = Image.FromStream(ms); image.Save(serverPath + fileName + ".png"); Response.HeaderEncoding = Encoding.UTF8; Response.Charset = "utf-8"; Response.Write("ok"); } catch (Exception e) { DebugHelper.Info(e.Message); Response.HeaderEncoding = Encoding.UTF8; Response.Charset = "utf-8"; Response.Write("error"); } }
好了 大功告成!