C#调用HTTP POST请求上传图片

现在很多B/S系统的开发都是通过API方式来进行的,一般服务端会开放一个API接口,客户端调用API接口来实现图片或文件上传的功能。

前段时间碰到需要使用POST请求上传图片的功能,好久没写了,重新整理下函数,方便后续使用。

为了使用的通用性,函数做了一定的封装,具体代码如下:

 1     public static void UploadImage(string uploadUrl,string imgPath,string fileparameter="file")
 2         {
 3             HttpWebRequest request = WebRequest.Create(uploadUrl) as HttpWebRequest;
 4             request.AllowAutoRedirect = true;
 5             request.Method = "POST";
 6 
 7             string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
 8             request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
 9             byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
10             byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
11 
12             int pos = imgPath.LastIndexOf("/");
13             string fileName = imgPath.Substring(pos + 1);
14 
15             //请求头部信息 
16             StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\""+fileparameter+"\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
17             byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
18 
19             FileStream fs = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
20             byte[] bArr = new byte[fs.Length];
21             fs.Read(bArr, 0, bArr.Length);
22             fs.Close();
23 
24             Stream postStream = request.GetRequestStream();
25             postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
26             postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
27             postStream.Write(bArr, 0, bArr.Length);
28             postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
29             postStream.Close();
30 
31             HttpWebResponse response = request.GetResponse() as HttpWebResponse;
32             Stream instream = response.GetResponseStream();
33             StreamReader sr = new StreamReader(instream, Encoding.UTF8);
34             string content = sr.ReadToEnd();
35         }

使用起来也比较方便,调用方法如下:

UploadImage("图上上传接口地址","本地图片文件路径","接口提供的上传参数名称,没有默认为file");

例如:UploadImage("http://xxx.com/upload","C:/test.jpg","upload");

posted @ 2021-03-03 12:35  薄心之心  阅读(3896)  评论(0编辑  收藏  举报