一、C# Winform或控制台
/// <summary> /// 通过http上传图片及传参数 /// </summary> /// <param name="imgPath">图片地址(绝对路径:D:\demo\img\123.jpg)</param> public void UploadImage(string imgPath) { var uploadUrl = "http://localhost:3020/upload/imgup"; var dic = new Dictionary<string, string>() { {"para1",1.ToString() }, {"para2",2.ToString() }, {"para3",3.ToString() }, }; var postData = Utils.BuildQuery(dic);//转换成:para1=1¶2=2¶3=3 var postUrl = string.Format("{0}?{1}", uploadUrl, postData);//拼接url HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest; request.AllowAutoRedirect = true; request.Method = "POST"; string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线 request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary; byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); int pos = imgPath.LastIndexOf("\\"); string fileName = imgPath.Substring(pos + 1); //请求头部信息 StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName)); byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString()); FileStream fs = new FileStream(imgPath, FileMode.Open, FileAccess.Read); byte[] bArr = new byte[fs.Length]; fs.Read(bArr, 0, bArr.Length); fs.Close(); Stream postStream = request.GetRequestStream(); postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); postStream.Write(bArr, 0, bArr.Length); postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); postStream.Close(); HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream instream = response.GetResponseStream(); StreamReader sr = new StreamReader(instream, Encoding.UTF8); string content = sr.ReadToEnd(); }
二、图片接收接口
[ValidateInput(false)] public JsonResult imgup(string para1,string para2,string para3) { if (Request.Files.Count > 0) { //传过来的图片 var file = Request.Files[0]; //保存到本地或服务器 } return new JsonResult { }; }
原文地址:https://www.cnblogs.com/pingming/p/8550802.html
时间: 2024-10-12 11:03:31