(轉 https://www.cnblogs.com/phonecom/p/08859d91a2dac3c409f5859dcb36cb48.html)
上傳、獲取臨時素材文件,媒體文件類型有圖片(image)、語音(voice)、視頻(video),普通文件(file) ,這里以上傳、下載圖片為例
上傳臨時素材文件
根據開發文檔,可以看出,需要三個參數access_token、type、media,access_token和type容易解決,media的話就要寫一個表單上傳過來
表單如下:
<form action="<{$upload_url}>" name="file" method="POST" enctype="multipart/form-data"><input type="file" name="image_file" value="選擇"><input type="submit" value="上傳">- </form>
表單提交后,即可開始上傳
private function upload_image($image_file) {$access_token = $this->get_access_token($this->corpid, $this->corpsecret);$type = 'image';//這里是個坑,臨時文件不能上傳,需要保存到某個路徑下再上傳$upload_dir = SYSTEM_DATA . "upload/test/";!is_dir($upload_dir) and mkdir($upload_dir, 0755, true);$file_path = $upload_dir . $image_file["name"];//這里用move_uploaded_file也可以copy($image_file["tmp_name"], $file_path);$post_data = array(//這里是個坑,要在前面加@(@是禁止將字符串中的斜杠解釋為轉義字符)"media" => "@" . $file_path,);$url = 'https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=' . $access_token . '&type=' . $type;$array_result = json_decode($this->https_request($url, $post_data), TRUE);return $array_result['media_id'];}
獲取臨時素材文件
根據開發文檔,可以看出,需要兩個參數access_token和media_id,media_id就是上面上傳時返回的media_id
private function download_image($media_id) {$access_token = $this->get_access_token($this->corpid, $this->corpsecret);$url = 'https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=' . $access_token . '&media_id=' . $media_id;$a = file_get_contents($url);//以讀寫方式打開一個文件,若沒有,則自動創建$download_dir = SYSTEM_DATA . "download/test";!is_dir($download_dir) and mkdir($download_dir, 0755, true);$resource = fopen($download_dir."/$media_id.jpg" , 'w+');//將圖片內容寫入上述新建的文件fwrite($resource, $a);//關閉資源fclose($resource);}
