上傳永久素材-圖片

//前臺

<form id="media" action="/UpLoadFile/Temporary_UploadPhoto"  method="post" enctype="multipart/form-data">
    <input type="file" name="media" />
    <input type="submit" value="上傳圖片" />
</form>


//後臺代碼

public JsonResult UploadPhoto(HttpPostedFileBase media)
{
//獲取上傳文件的字節數組
var buf = new byte[media.InputStream.Length];

//讀取數組
media.InputStream.Read(buf, 0, (int)media.InputStream.Length);

//獲取access_Token
var accessToken = MvcApplication1.Tools.Access_token_Tool.access_token;

//調用接口
string url = string.Format("https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={0}&type={1}", accessToken, "image");
//調用方法獲取返回的json字符串 url 接口 media.FileName 文件名 buf 字節數組
string resultUpload = HttpUploadPhoto(url, media.FileName, buf);

//獲取上傳後返回的結果狀態
var jsonObj = JsonConvert.DeserializeObject<DTO_return>(resultUpload);

return Json("");

}


/// <summary>
/// 獲取調用接口後的返回狀態
/// </summary>
/// <param name="url">接口</param>
/// <param name="path">圖片名</param>
/// <param name="bf">文件字節數組</param>
/// <returns></returns>
public static string HttpUploadPhoto(string url, string path, byte[] bf)
{
//access_Token
var accessToken = MvcApplication1.Tools.Access_token_Tool.access_token;

//初始化接口
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

CookieContainer cookieContainer = new CookieContainer();

//設置關聯的cookie值
request.CookieContainer = cookieContainer;

//請求跟隨是否重定向
request.AllowAutoRedirect = true;

//設置請求的方法
request.Method = "POST";

//Ticks 時間差
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 = path.LastIndexOf("\\");
string fileName = path.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());

//獲取字節序列的視圖(相當於from表單)
Stream postStream = request.GetRequestStream();
postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
postStream.Write(bf, 0, bf.Length);
postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
postStream.Close();

//發送請求並獲取相應迴應數據
HttpWebResponse response = request.GetResponse() as HttpWebResponse;

//將返回的數據放入視圖,再讀取出來
Stream instream = response.GetResponseStream();
StreamReader sr = new StreamReader(instream, Encoding.UTF8);
string content = sr.ReadToEnd();

return content;
}
發佈了32 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章