在調(diào)用公眾號(hào)接口https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=".$token."&type=".$type;
上傳永久素材文件總是返回"{\"errcode\":41005,\"errmsg\":\"media data missing\"}"
經(jīng)過多次測(cè)試使用下面的方式,可以正常上傳
//調(diào)用測(cè)試
protected static $url;
protected static $delimiter;
protected static $instance;
public function index()
{
? ? ? ? static::$delimiter = uniqid();
$basename = Request::instance()->root();
if (pathinfo($basename, PATHINFO_EXTENSION) == 'php') {
? ? $basename = dirname($basename);
}
? ? ? ? $result=$this->wxAddMaterial($token,$basename.'/upload/images/gnlog.jpg','image');
? ? }
// 新增其他類型永久素材
public function wxAddMaterial($token,$filename='',$type='') {
? ? // 設(shè)置請(qǐng)求參數(shù)
? ? static::$url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=".$token."&type=".$type;
? ? $filePath = str_replace('\\', '/', $filename);
? ? // 發(fā)送請(qǐng)求
? ? $imginfo=pathinfo($filePath);
? ? $fields = array(
? ? ? ? 'media'=>file_get_contents(".".$filePath),
? ? ? ? 'filename'=>$imginfo["basename"],
);
? ? $res = $this->putPart( $fields);
? ? // 發(fā)送請(qǐng)求
? ? return $res;
}
//推送文件流
public function putPart($param) {
? ? $post_data = static::buildData($param);
? ? $curl = curl_init(static::$url);
? ? curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
? ? curl_setopt($curl, CURLOPT_POST, true);
? ? curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
? ? curl_setopt($curl, CURLOPT_HTTPHEADER, [
? ? ? ? "Content-Type: multipart/form-data; boundary=" . static::$delimiter,
? ? ? ? "Content-Length: " . strlen($post_data)
]);
? ? $response = curl_exec($curl);
? ? curl_close($curl);
? ? return $response;
}
//編譯請(qǐng)求頭格式和數(shù)據(jù)流
private static function buildData($param){
? ? $data = '';
? ? $eol = "\r\n";
? ? $upload = $param['media'];
? ? unset($param['media']);
? ? foreach ($param as $name => $content) {
? ? ? ? $data .= "--" . static::$delimiter . "\r\n"
? ? ? ? ? ? . 'Content-Disposition: form-data; name="' . $name . "\"\r\n\r\n"
? ? ? ? ? ? . $content . "\r\n";
}
? ? $data .= "--" . static::$delimiter . $eol
? ? ? ? . 'Content-Disposition: form-data; name="media"; filename="' . $param['filename'] . '"' . "\r\n"
? ? ? ? . 'Content-Type:application/octet-stream'."\r\n\r\n";
? ? $data .= $upload . "\r\n";
? ? $data .= "--" . static::$delimiter . "--\r\n";
? ? return $data;
}
根據(jù)自己的實(shí)際情況稍作修改