微信企业号-上传、获取临时素材文件

(转 https://www.cnblogs.com/phonecom/p/08859d91a2dac3c409f5859dcb36cb48.html)

上传、获取临时素材文件,媒体文件类型有图片(image)、语音(voice)、视频(video),普通文件(file) ,这里以上传、下载图片为例

上传临时素材文件      

 根据开发文档,可以看出,需要三个参数access_token、type、media,access_token和type容易解决,media的话就要写一个表单上传过来
表单如下:
  1. <form action="<{$upload_url}>" name="file" method="POST" enctype="multipart/form-data">
  2. <input type="file" name="image_file" value="选择">
  3. <input type="submit" value="上传">
  4. </form>
表单提交后,即可开始上传
  1. private function upload_image($image_file) {
  2. $access_token = $this->get_access_token($this->corpid, $this->corpsecret);
  3. $type = 'image';
  4. //这里是个坑,临时文件不能上传,需要保存到某个路径下再上传
  5. $upload_dir = SYSTEM_DATA . "upload/test/";
  6. !is_dir($upload_dir) and mkdir($upload_dir, 0755, true);
  7. $file_path = $upload_dir . $image_file["name"];
  8. //这里用move_uploaded_file也可以
  9. copy($image_file["tmp_name"], $file_path);
  10. $post_data = array(
  11. //这里是个坑,要在前面加@(@是禁止将字符串中的斜杠解释为转义字符)
  12. "media" => "@" . $file_path,
  13. );
  14. $url = 'https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=' . $access_token . '&type=' . $type;
  15. $array_result = json_decode($this->https_request($url, $post_data), TRUE);
  16. return $array_result['media_id'];
  17. }

获取临时素材文件

根据开发文档,可以看出,需要两个参数access_token和media_id,media_id就是上面上传时返回的media_id
  1. private function download_image($media_id) {
  2. $access_token = $this->get_access_token($this->corpid, $this->corpsecret);
  3. $url = 'https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=' . $access_token . '&media_id=' . $media_id;
  4. $a = file_get_contents($url);
  5. //以读写方式打开一个文件,若没有,则自动创建
  6. $download_dir = SYSTEM_DATA . "download/test";
  7. !is_dir($download_dir) and mkdir($download_dir, 0755, true);
  8. $resource = fopen($download_dir."/$media_id.jpg" , 'w+');
  9. //将图片内容写入上述新建的文件
  10. fwrite($resource, $a);
  11. //关闭资源
  12. fclose($resource);
  13. }

猜你喜欢

转载自www.cnblogs.com/alexguoyihao/p/9259002.html