我正在尝试使用cURL将图像发布到我的REStful服务的图片上传方法。
rest式服务需要以下格式的请求:-
Accept: application/json
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Content-Length: 782
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary5dQ1ta4rvOvWtjff
它还使用一个授权令牌字符串。
下面是我的PHP代码:-$_FILES['file']作为$data传递给this,作为旁注。
move_uploaded_file($data["tmp_name"], "../uploaded_files/images/".$data["name"]);
$data_string = "@".realpath("../uploaded_files/images/".$data["name"]).";type=image/png";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CERTINFO, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$boundary = md5(date('U'));
$http_headers = array(
'Authorization: Bearer '.$_SESSION['Auth'],
'Accept: application/json',
'Accept-Encoding: gzip,deflate,sdch',
'Content-Length: '.$data['size'],
"Content-Type: multipart/form-data; boundary=$boundary"."'r'n"
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $http_headers);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
据我所知,这应该匹配和工作,但它没有。当我包含Content-Length(因为它是必需的,否则将生成一个411代码)时,服务器冻结,然后在很长一段时间后生成这个错误:-
SSL read: error:00000000:lib(0):func(0):reason(0), errno 0
有谁知道我可能做错了什么吗?我能够使用上面的代码成功地发布JSON和其他内容类型,它似乎只是特定于我试图以这种方式发布图像。
编辑:我被告知文件上传的@方法已被弃用,所以我调整了我的代码如下:-
$path = realpath("../upload_files/images/".$data["name"]);
$cfile = curl_file_create($path, 'image/png','file_upload');
$data_string = array('file_upload' => $cfile);
但是现在它生成一个400状态码"错误的请求"。我使用这种方法是错误的,还是我错过了什么?我也试过下面的面向对象的版本,但它产生了同样的问题。
$cfile = new CURLFile($path,'image/png','file_upload');
这个问题很可能与您的请求的Content-Type
有关。根据给定的格式判断,应设置为multipart/form-data
,即发送的数据应编码为multipart/form-data
。根据手册,为了将Content-Type
头设置为multipart/form-data
,您必须将CURLOPT_POSTFIELDS
选项设置为array
(不是url编码的字符串,如您的代码)。在这种情况下,数据将自动编码为multipart/form-data
。
move_uploaded_file($data["tmp_name"], "../uploaded_files/images/".$data["name"]);
$path = realpath("../uploaded_files/images/".$data["name"]);
$data = array('file' => "@$path;type=image/png");
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
...
BTW: @
前缀仅在PHP 5.5.0之后弃用。
我在这里发现了这个问题。
我的cURL试图连接到的rest式服务需要设置Content Disposition头,这是cURL故意忽略的,因为它设置了自己的边界。
在这种情况下,它是不可能完成我试图做的是使用这个API的方法,与PHP。
也就是说,除非有人知道其他php库可以设置内容配置。