微信学习笔记之四(媒体文件的上传与下载)


1. 上传图片

$this->weixin_upload('image','./');

/*
返回结果
/*
{
    "type": "image",
    "media_id": "QQ9nj-7ctrqA8t3WKU3dQN24IuFV_516MfZRZNnQ0c-BFVkk66jUkPXF49QE9L1l",
    "created_at": 1389793969
}
*/

2. 上传语音

$this->weixin_upload('voice','./');

/*
返回结果
{
    "type": "voice",
    "media_id": "5Idx79V9E3XfBCz_A50gr1a1_klgPpJnb_eq73yz0bn-prhIsNlwI3n6jQgshmWk",
    "created_at": 1389794760
}

*/

3. 上传视频

$this->weixin_upload('video','./');

/*
返回结果
{
    "type": "video",
    "media_id": "Jm-Wq0nXtA_oN1qNydQRP03dCsB0R2t5gCHDM3QNkBmMRE1WBaorVJNQTBRHvK9-",
    "created_at": 1389794768
}

*/

4. 上传缩略图

$this->weixin_upload('thumb','./');

/*
返回结果
{
    "type": "thumb",
    "thumb_media_id": "2RhP0caRKHVOmZO5AKelHkK--vqPPwgUaRp5-WE63dvmmPRWiYVKgvNblIp_gv79",
    "created_at": 1389794771
}
*/

5. 下载

$this->weixin_download('你文件的media',$type = '文件的后缀名');

附录:

第一个函数:weixin_upload

public function weixin_upload($type = 'image',$filepath = './')

	$access_token = $this->get_token();
	$filedata = array('media' => "@".$filepath);

	$url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=$access_token&type=$type";
	$res = https_request($url,$filedata);
	return json_decode($res);
}

第二个函数:https_request:

 public function https_request($url, $data = null){
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_URL, $url);
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
      if (!empty($data)){
          curl_setopt($curl, CURLOPT_POST, 1);
          curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
      }
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
      $output = curl_exec($curl);
      curl_close($curl);
      return $output;
  }

第三个函数:get_token;

public function get_token(){
	 $this->_appid = '你的appid';
	 $this->_sercet = '你的appsercet';
	 $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->_appid&secret=$this->_sercet";
	 //当然 这里 最好做个缓存 
	 $res = file_get_contents($url);
	 $res = json_decode($res);

	 return $res->access_token;
 }

 第四个函数:weixin_download


public function weixin_download($media_id='',$type='jpg'){
     
	 $token = $this->get_token();
	 $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=$token&media_id=$media_id";
	 $filedata= file_get_contents($url);
	 $newpath = 你的文件存放路径."文件名.".$type;
 	 file_put_contents($newpath,$filedata);
 }

上传的多媒体文件有格式和大小限制,如下:

?  图片(image): 128K,支持JPG格式

?  语音(voice):256K,播放长度不超过60s,支持AMR\MP3格式

?  视频(video):1MB,支持MP4格式

?  缩略图(thumb):64KB,支持JPG格式

媒体文件在后台保存时间为3天,即3天后media_id失效。


 token 需要缓存详见:
 笔记二 token 的获取

 本文参考来源:http://www.cnblogs.com/txw1958/p/weixin80-upload-download-media-file.html













微信学习笔记之四(媒体文件的上传与下载)

上一篇:微信练手-环境准备(1)


下一篇:用c#开发微信 (10) JS-SDK 基本用法- 分享接口“发送到朋友”