在调用公众号接口https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=".$token."&type=".$type;
上传永久素材文件总是返回"{\"errcode\":41005,\"errmsg\":\"media data missing\"}"
经过多次测试使用下面的方式,可以正常上传
//调用测试
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='') {
// 设置请求参数
static::$url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=".$token."&type=".$type;
$filePath = str_replace('\\', '/', $filename);
// 发送请求
$imginfo=pathinfo($filePath);
$fields = array(
'media'=>file_get_contents(".".$filePath),
'filename'=>$imginfo["basename"],
);
$res = $this->putPart( $fields);
// 发送请求
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;
}
//编译请求头格式和数据流
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;
}
根据自己的实际情况稍作修改