在實現微信圖片上傳時,因為文件是一個文件,無法向字符串一樣通過參數一樣直接寫在請求地址中,
我自己做了一個頁面抓取了一下請求,自己用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; }