調用微信接口自動實現上傳本地圖片


在實現微信圖片上傳時,因為文件是一個文件,無法向字符串一樣通過參數一樣直接寫在請求地址中,

 我自己做了一個頁面抓取了一下請求,自己用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("\r\n--" + boundary + "\r\n");
            byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            //請求頭部信息 
            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));
            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;
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM