/** * 下载一个素材 * @param string $mediaId 媒体id,通过上传获得 * @param string $toFile 可选,下载到文件的绝对路径,不填则默认路径为RES_ROOT/$mediaId * @return integer 下载到的文件大小(失败时返回false) * @throws ApiException */ public function download($mediaId, $toFile = null) { //使用http协议 // $this->url = str_replace('https', 'http', $this->url); $url = $this->url . '/get?access_token=' . $this->accessToken . '&media_id=' . $mediaId; $httpClient = new HttpClient($url); $httpClient->get(30); if ($httpClient->getStatus() != 200 || $httpClient->getResponse() == '') { throw ApiException::throws(ApiException::HTTP_ERROR_CODE, 'status code: ' . $httpClient->getStatus()); return false; } $header = $httpClient->getHeader(); $contentType = $header['Content-Type'][0]; //Content-Type为text/时表示带有errcode错误信息 if (!isset($header['Content-Type']) || stripos($contentType, 'text') !== false) { $result = json_decode($httpClient->getResponse(), true); if (!$result) { throw ApiException::throws(ApiException::JSON_DECODE_ERROR_CODE, 'response: ' . $httpClient->getResponse()); } if (isset($result['errcode']) && $result['errcode'] != 0) { throw new ApiException($result['errmsg'], $result['errcode']); //非0状态码 } return false; } //写入文件 if (empty($toFile)) { if (!is_dir(RES_ROOT . '/media')) { mkdir(RES_ROOT . '/media'); chmod(RES_ROOT . '/media', 0775); } $toFile = RES_ROOT . "/media/{$mediaId}" . $this->parseExtension($contentType); } file_put_contents($toFile, $httpClient->getResponse()); return filesize($toFile); }