JeffreySu/WeiXinMPSDK — pull request #39 by zeusro (2014-08-20 01:50:50+00:00)
Title: Media

///

/// 上传/下载媒体基类
///

public class Media
{
///

/// 调用接口凭证
///

public string access_token { get; set; }

///

/// 媒体文件类型，分别有图片（image）、语音（voice）、视频（video）和缩略图（thumb）
///

public BaseInfoTYPE type { get; set; }

///

/// 完整路径+文件名
///

public string fileName { get; set; }

///

/// 下载时用到
///

public string mediaId { get; set; }

///

/// 上传媒体文件
///

///
///
///
///
public UploadResultJson Upload()
{
var url = string.Format("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", access_token, type.ToString());
var fileDictionary = new Dictionary();
fileDictionary["media"] = fileName;
return HttpUtility.Post.PostFileGetJson(url, null, fileDictionary, null);
}

///

/// 下载多媒体文件,至少要实例化access_token，type，fileName，mediaId三个属性
///

///
///
/// 完整路径E:\testpic_{0}.jpg
///
public bool DownloadMedia()
{
using (MemoryStream ms = new MemoryStream())
{
var url = string.Format("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}",
access_token, mediaId);
Get.Download(url, ms);
if (ms.Length < 1)
{
return false;
}
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
ms.Position = 0;
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = ms.Read(buffer, 0, buffer.Length)) != 0)
{
fs.Write(buffer, 0, bytesRead);
}
fs.Flush();
}

}
return File.Exists(fileName);
}

}