使用c#后端上传永久素材,临时素材同理。
此贴为日常开发中应用实例,微信文档说明对于我这种小白来说属实有点简单了,所以其中踩了很多坑。
微信接口开发并没有实际说明该如何正确的封装请求头,下面请看代码
public string UploadImg(string UploadFileName)
{
if (string.IsNullOrWhiteSpace(access_token))
{
throw new Exception("access_token为空,上传失败!");
}
//type媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
var url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=" + access_token + "&type=image";
var folderPath = BaseAppConfig.UploadedFilesFolder;
string filePath = null;
// 遍历文件夹中的所有文件和子文件夹
foreach (string file in Directory.GetFiles(folderPath, "*", SearchOption.AllDirectories))
{
if (Path.GetFileName(file) == UploadFileName)
{
filePath = file;
break;
}
}
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
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 = filePath.LastIndexOf("\\");
string fileName = filePath.Substring(pos + 1);
//请求头部信息
StringBuilder sbHeader =
new StringBuilder(
string.Format(
"Content-Disposition:form-data;name=\"media\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n",
fileName));
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
FileStream fs = new FileStream(filePath, 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;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream instream = response.GetResponseStream();
StreamReader sr = new StreamReader(instream, Encoding.UTF8);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
return content;
}
其中的UploadFileName不用管,我这里是为了项目的业务需要通过文件名称去找到项目中的文件,所以这里只需要把filePath调整正确就行了,filePath为文件的绝对路径。HttpWebRequest request封装为重点,封装不正确就会导致上传不成功。