【C#】HTTP post 上传图片及参数

一、具体代码

 1 /// <summary>
 2         /// 通过http上传图片及传参数
 3         /// </summary>
 4         /// <param name="imgPath">图片地址(绝对路径:D:\demo\img\123.jpg)</param>
 5         public void UploadImage(string imgPath)
 6         {
 7             var uploadUrl = "http://localhost:3020/upload/imgup";
 8             var dic = new Dictionary<string, string>() {
 9                     {"para1",1.ToString() },
10                     {"para2",2.ToString() },
11                     {"para3",3.ToString() },
12                 };
13             var postData = Utils.BuildQuery(dic);//转换成:para1=1&para2=2&para3=3
14             var postUrl = string.Format("{0}?{1}", uploadUrl, postData);//拼接url
15             HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
16             request.AllowAutoRedirect = true;
17             request.Method = "POST";
18 
19             string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
20             request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
21             byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
22             byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
23 
24             int pos = imgPath.LastIndexOf("\\");
25             string fileName = imgPath.Substring(pos + 1);
26 
27             //请求头部信息 
28             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));
29             byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
30 
31             FileStream fs = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
32             byte[] bArr = new byte[fs.Length];
33             fs.Read(bArr, 0, bArr.Length);
34             fs.Close();
35 
36             Stream postStream = request.GetRequestStream();
37             postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
38             postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
39             postStream.Write(bArr, 0, bArr.Length);
40             postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
41             postStream.Close();
42 
43             HttpWebResponse response = request.GetResponse() as HttpWebResponse;
44             Stream instream = response.GetResponseStream();
45             StreamReader sr = new StreamReader(instream, Encoding.UTF8);
46             string content = sr.ReadToEnd();
47         }

可以把第7行的直接写成拼接形式,这样第8-13行可以删掉,第十四行可换成:

var postUrl = uploadUrl;

 

设置参数名:

将第28行,name后面的file修改成你想要的参数名即可。

 

二、具体使用

string imgPath = “”;//绝对地址
string posjson = UploadImage(string imgPath);

 

上一篇:Python图片上画矩形 点 连线 文字标注并保存


下一篇:10 行Python代码实现批量压缩图片500 张,面试必学