WordPress自带Http请求Post上传文件方法

WordPress的wp_remote_post函数用来提交Post请求非常方便,但用于上传文件时遇到一些问题。在做微信公众号开发时经常需要上传图片,可以使用WordPress自带的Http请求类来实现。

下面是微信公众号开发上传图片的示例:

$url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=$access_token";
$file = new CURLFile($file);
$Http = new WP_Http_Curl;
$args = array(
	'method' => 'POST',
	'sslverify' => false,
	'body' => array('media'=>$file),
);
$res = wp_remote_retrieve_body($Http->request($url, $args));
$res = json_decode($res, true);

代码释义:

  • $url为公众号上传图片接口的地址;
  • $file为文件路径,在PHP版本高于5.5时必须使用CURLFile对象指向文件;
  • 提交请求使用了WP_Http_Curl类;
  • wp_remote_retrieve_body函数提取公众号平台返回的JSON数据;
  • json_decode将返回的JSON数据转换为数组。
阿里云