php - 类 CURLFile 的对象无法转换为字符串

标签 php curl php-curl

如何通过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/fileCURLOPT_SAFE_UPLOAD = false )并始终使用 curl_file_create() .

关于php - 类 CURLFile 的对象无法转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58696598/

相关文章:

PHP cURL 不存储 session cookie...如何解决这个问题?

php - Paypal 使用 PHP cURL 获取交易详细信息

PHP cURL - 如何通过 HTTP 请求将变量的内容作为文件上传?

php - 7.4.2 版本的 PHP cURL 扩展是否支持带有 HTTP/3 的 cURL

phpredis 函数 mSet 与 ttl

PHPStorm自动完成 Twig 变量

php - 如何让 DOMDocument 在 PHP 中写 standalone=yes?

php - 以 PayPal 形式传递自定义数据

java - RestTemplate 用法

ruby-on-rails - RVM、Ruby 2.4.1 错误