微信公众号开发永久素材上传

使用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封装为重点,封装不正确就会导致上传不成功。

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值