如何通过cURL实现图片上传?
我正在使用沙箱 api 将 pdf 文件转换为 .txt 文件。如果我使用“https://s3.amazonaws.com/sample.pdf”的 pdf 路径为 $sourceFile variable
那么它的工作正常。但是如果我使用系统路径“test.pdf”,那么它就不起作用了。
我试图通过 curl_file_create
,但它给出了以下错误:
Recoverable fatal error: Object of class CURLFile could not be converted to string in line.
我使用的是 PHP 版本 7.3.0
<?php
error_reporting(E_ALL);
$endpoint = "https://api.xxx.com/v1/jobs";
$apiKey = "GiVU******FR48H";
$sourceFile = "https://s3.amazonaws.com/sample.pdf";//new CurlFile("test.pdf");
$targetFormat = "txt";
$postData = array(
"source_file" => $sourceFile,
"target_format" => $targetFormat
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERPWD, $apiKey . ":");
$body = curl_exec($ch);
curl_close($ch);
$response = json_decode($body, true);
echo "Response:\n---------\n";
echo"<pre>";
print_r($response);
?>
Response: ---------
Array
(
[id] => 8442473
[key] => GiVU******FR48H
[status] => initialising
[sandbox] =>
[created_at] => 2019-11-12T10:35:01Z
[finished_at] =>
[import] => Array
(
[id] => 671784
[url] => https://s3.amazonaws.com/sample.pdf
[status] => initialising
)
[target_files] => Array
(
)
[target_format] => txt
[credit_cost] => 0
)
上面的例子也给了我很好的输出。如果我更换 amazonaws
来自 system path
然后它不会给出任何响应。
最佳答案
CURLOPT_SAFE_UPLOAD
始终设置为 false
并且 curl 期望文件因此作为字符串( @/path/to/file
)传递。在您的情况下,代码将文件作为对象发送,因为它使用 curl_file_create()
有空的时候。
当CURLOPT_SAFE_UPLOAD
设置为 false
,你不应该使用 curl_file_create()
(这是向后兼容的标志)。
另外,尝试设置 CURLOPT_POSTFIELDS
之后 CURLOPT_SAFE_UPLOAD
( see here why )。
PHP 5.x 是 not supported anymore我建议摆脱旧语法( @/path/to/file
和 CURLOPT_SAFE_UPLOAD = false
)并始终使用 curl_file_create()
.
关于php - 类 CURLFile 的对象无法转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58696598/