调用微信接口自动实现上传本地图片

在实现微信图片上传时,因为文件是一个文件,无法向字符串一样通过参数一样直接写在请求地址中,

 我自己做了一个页面抓取了一下请求,自己用C#代码拼接了一个请求。

public  string HttpUploadFile() {
            string url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=****************&type=image";


            #region 本地图片

            string path = "E:\110.jpg";
            int pos = path.LastIndexOf("\");
            string fileName = path.Substring(pos + 1);
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            byte[] bArr = new byte[fs.Length];
            fs.Read(bArr, 0, bArr.Length);
            fs.Close(); 

            #endregion


            #region 获取从表单中提交的图片

            //var file = context.Request.Files[0];
            //byte[] bArr = new byte[file.InputStream.Length];
            //file.InputStream.Read(bArr, 0, bArr.Length);
            //file.InputStream.Close();

            #endregion

         

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            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("
--" + boundary + "
");
            byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("
--" + boundary + "--
");

            //请求头部信息 
            StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name="file";filename="{0}"
Content-Type:application/octet-stream

", fileName));
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
          
            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 respStream = response.GetResponseStream();
            StreamReader sw = new StreamReader(respStream, Encoding.UTF8);
            string str = sw.ReadToEnd();

            return str;
        }
原文地址:https://www.cnblogs.com/xinxinzhihuo/p/5732724.html