1.WebClient方式:注意是只能以byte[]流的方式上传,参数只能拼接在url上。适用于winfrom 。
--前端调用
//将图片转为byte数组 byte[] pic = SaveImage(@"E:CPS_VMSAlarmCSharpDemogirl.jpg"); //方式一 WebClient web = new WebClient(); web.UploadData("http://localhost:20007/TMSAPI/uploadPic?carnum=111111", CompressBytes(pic)); ---------------------- //压缩字节 //1.创建压缩的数据流 //2.设定compressStream为存放被压缩的文件流,并设定为压缩模式 //3.将需要压缩的字节写到被压缩的文件流 public static byte[] CompressBytes(byte[] bytes) { using (MemoryStream compressStream = new MemoryStream()) { using (var zipStream = new GZipStream(compressStream, CompressionMode.Compress)) zipStream.Write(bytes, 0, bytes.Length); return compressStream.ToArray(); } } /// <summary> /// 将图片以二进制流 /// </summary> /// <param name="path"></param> /// <returns></returns> public byte[] SaveImage(String path) { FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); //将图片以文件流的形式进行保存 BinaryReader br = new BinaryReader(fs); byte[] imgBytesIn = br.ReadBytes((int)fs.Length); //将流读入到字节数组中 return imgBytesIn; }
-----服务端接收
public string uploadPic() { try { string carnum = HttpContext.Request["carnum"]; string type = HttpContext.Request["type"]; if (string.IsNullOrEmpty(carnum)) return "0"; //文件夹路径 string filestr = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg"; string urlPath = "upload/MointerPic/" + DateTime.Now.ToString("yyyy-MM-dd") + "/" + type + "/"; string filePath =HttpContext.Server.MapPath("/" + urlPath); // 文件路径 string directoryName = Path.GetDirectoryName(filePath); if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName); int lang = HttpContext.Request.TotalBytes; byte[] bytes = Decompress(HttpContext.Request.BinaryRead(lang)); string content = System.Text.Encoding.UTF8.GetString(bytes); FileStream fStream = new FileStream(filePath + filestr, FileMode.Create, FileAccess.Write); BinaryWriter bw = new BinaryWriter(fStream); bw.Write(bytes); bw.Close(); fStream.Close(); new MonitInfoDA().Add(new MonitInfo() { CarNum = carnum, MonitType = type, PicPath = urlPath + filestr, LastTime = DateTime.Now }); return "1"; } catch (Exception ex) { HttpContext.Response.Write(ex.Message); HttpContext.Response.End(); return "0"; } } //解压缩字节 //1.创建被压缩的数据流 //2.创建zipStream对象,并传入解压的文件流 //3.创建目标流 //4.zipStream拷贝到目标流 //5.返回目标流输出字节 public byte[] Decompress(byte[] bytes) { using (var compressStream = new MemoryStream(bytes)) { using (var zipStream = new GZipStream(compressStream, CompressionMode.Decompress)) { using (var resultStream = new MemoryStream()) { zipStream.CopyTo(resultStream); return resultStream.ToArray(); } } } }
-------------------------------------------------------------
2.方式2: 以参数的方式Post上传是通过常规的以base64上传图片,适用winform 和webform
----前端调用
//方式二 Hashtable ht = new Hashtable(); ht["plateNo"] = "1167"; ht["workspace"] = "5ae11168a4647d3e98d1944ec13"; byte[] pic3 = SaveImage(@"E:CPS_VMSAlarmCSharpDemogirl.jpg"); string str = Convert.ToBase64String(pic3); ht["file"] = str;//图片base64 var result = PostURL.Post("XXX.api", ht); -------------- //压缩字节 //1.创建压缩的数据流 //2.设定compressStream为存放被压缩的文件流,并设定为压缩模式 //3.将需要压缩的字节写到被压缩的文件流 public static byte[] CompressBytes(byte[] bytes) { using (MemoryStream compressStream = new MemoryStream()) { using (var zipStream = new GZipStream(compressStream, CompressionMode.Compress)) zipStream.Write(bytes, 0, bytes.Length); return compressStream.ToArray(); } } /// <summary> /// 将图片以二进制流 /// </summary> /// <param name="path"></param> /// <returns></returns> public byte[] SaveImage(String path) { FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); //将图片以文件流的形式进行保存 BinaryReader br = new BinaryReader(fs); byte[] imgBytesIn = br.ReadBytes((int)fs.Length); //将流读入到字节数组中 return imgBytesIn; }
----服务端接收
/// <summary> /// 接收Base64编码格式的图片 /// </summary> [HttpPost] public void Upload() { //获取base64编码的图片 HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"]; string text = context.Request.Form["file"]; string val = context.Request.Form["plateNo"]; //获取文件储存路径 string path = context.Request.MapPath("~/"); //获取当前项目所在目录 string datetime = GetTimeStamp(); string suffix = ".jpg"; //文件的后缀名根据实际情况 string strPath = path + "App_Data/" + datetime + suffix; //获取图片并保存 Base64ToImg(text).Save(strPath); } //解析base64编码获取图片 private Bitmap Base64ToImg(string base64Code) { MemoryStream stream = new MemoryStream(Convert.FromBase64String(base64Code)); return new Bitmap(stream); }
------------------------------------------------------------
3.以文件和api方式上传图片
--前端调用
NameValueCollection ht = new NameValueCollection(); ht["carnum"] = "VH2467"; ht["workspace"] = "5ae68a4647d3e98d1944ec13"; string picstr=@"E:CPS_VMSAlarmCSharpDemogirl.jpg"; var result = PostURL.HttpUploadFile("http://localhost:20007/TMSAPI/uploadPic2", new string[] { picstr }, ht);
--HttpUploadFile方法
private static readonly Encoding DEFAULTENCODE = Encoding.UTF8; /// <summary> /// HttpUploadFile /// </summary> /// <param name="url"></param> /// <param name="file"></param> /// <param name="data"></param> /// <returns></returns> public static string HttpUploadFile(string url, string file, NameValueCollection data) { return HttpUploadFile(url, file, data, DEFAULTENCODE); } /// <summary> /// HttpUploadFile /// </summary> /// <param name="url"></param> /// <param name="file"></param> /// <param name="data"></param> /// <param name="encoding"></param> /// <returns></returns> public static string HttpUploadFile(string url, string file, NameValueCollection data, Encoding encoding) { return HttpUploadFile(url, new string[] { file }, data, encoding); } /// <summary> /// HttpUploadFile /// </summary> /// <param name="url"></param> /// <param name="files"></param> /// <param name="data"></param> /// <returns></returns> public static string HttpUploadFile(string url, string[] files, NameValueCollection data) { return HttpUploadFile(url, files, data, DEFAULTENCODE); } /// <summary> /// HttpUploadFile /// </summary> /// <param name="url"></param> /// <param name="files"></param> /// <param name="data"></param> /// <param name="encoding"></param> /// <returns></returns> public static string HttpUploadFile(string url, string[] files, NameValueCollection data, Encoding encoding) { string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); byte[] boundarybytes = Encoding.ASCII.GetBytes(" --" + boundary + " "); byte[] endbytes = Encoding.ASCII.GetBytes(" --" + boundary + "-- "); //1.HttpWebRequest HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.ContentType = "multipart/form-data; boundary=" + boundary; request.Method = "POST"; request.KeepAlive = true; request.Credentials = CredentialCache.DefaultCredentials; using (Stream stream = request.GetRequestStream()) { //1.1 key/value string formdataTemplate = "Content-Disposition: form-data; name="{0}" {1}"; if (data != null) { foreach (string key in data.Keys) { stream.Write(boundarybytes, 0, boundarybytes.Length); string formitem = string.Format(formdataTemplate, key, data[key]); byte[] formitembytes = encoding.GetBytes(formitem); stream.Write(formitembytes, 0, formitembytes.Length); } } //1.2 file string headerTemplate = "Content-Disposition: form-data; name="{0}"; filename="{1}" Content-Type: application/octet-stream "; byte[] buffer = new byte[4096]; int bytesRead = 0; for (int i = 0; i < files.Length; i++) { stream.Write(boundarybytes, 0, boundarybytes.Length); string header = string.Format(headerTemplate, "file" + i, Path.GetFileName(files[i])); byte[] headerbytes = encoding.GetBytes(header); stream.Write(headerbytes, 0, headerbytes.Length); using (FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read)) { while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { stream.Write(buffer, 0, bytesRead); } } } //1.3 form end stream.Write(endbytes, 0, endbytes.Length); } //2.WebResponse HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader stream = new StreamReader(response.GetResponseStream())) { return stream.ReadToEnd(); } }
--api端
public string uploadPic2() { try { string carnum = HttpContext.Request["carnum"]; string type = HttpContext.Request["type"]; if (string.IsNullOrEmpty(carnum)) return "0"; //文件夹路径 string filestr = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg"; string urlPath = "upload/MointerPic/" + DateTime.Now.ToString("yyyy-MM-dd") + "/" + type + "/"; string filePath = HttpContext.Server.MapPath("/" + urlPath); // 文件路径 string directoryName = Path.GetDirectoryName(filePath); if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName); if (HttpContext.Request.Files.Count>0) { HttpPostedFileBase f = Request.Files[0]; f.SaveAs(directoryName+"\002.jpg"); } return "1"; } catch (Exception ex) { HttpContext.Response.Write(ex.Message); HttpContext.Response.End(); return "0"; } }