【发布时间】:2014-08-23 20:51:03
【问题描述】:
我正在尝试使用 cURL 将图像发布到我的 RESTful 服务的图片上传方法。
restful 服务需要以下格式的请求:-
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 传递给它,作为旁注。
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');
【问题讨论】:
-
@filename 用于文件上传的 API 已弃用。您可以改用 CURLFile 类。
-
我已经调整了代码以使用该类,但是现在我收到了代码 400 错误请求。
-
调试CURL,看看发送了什么header/body。