上传永久素材-图片

//前台


   
   


//后台代码

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(resultUpload);

return Json("");

}


///
/// 获取调用接口后的返回状态
///

/// 接口
/// 图片名
/// 文件字节数组
///
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;
}

你可能感兴趣的:(微信)