如何使用 cURL 将 PDF 内容发布为 application/pdf

Jer*_*eed 4 php pdf curl

我是 cURL 新手,通常使用 .NET 或 JQuery 发布到 Web API,但我需要使用现有的 PHP 实现将内容类型为 application/pdf 的 PDF 发布到 Web API。

现有的实现仅 POST 和接收 JSON 数据,因此非常简单。当我尝试将代码更改为将应用程序/pdf 内容发布到另一个端点时,我不断收到以下错误:

文件类型错误。可接受的内容类型包括应用程序/pdf、文本/富文本、文本/纯文本、图像/jpeg。

这是我正在使用的代码:

$curl = curl_init($url);  
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  
curl_setopt($curl, CURLOPT_FAILONERROR, false);  
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);  
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/pdf'),   
                                           $auth_header));   
curl_setopt($curl, CURLOPT_POST, 1);                                         
curl_setopt($curl, CURLOPT_POSTFIELDS, file_get_contents('C:\MyFile.pdf'));  
$response = curl_exec($curl);  
if (!$response) {  
  $response = curl_error($curl);  
}  
curl_close($curl);  
Run Code Online (Sandbox Code Playgroud)

我已经检查过该 PDF 是否是有效的 PDF,甚至尝试了其他几个 PDF。我还设置了 cURL 选项来写入错误日志,这表明 cURL 正在将标头中的内容类型设置为 application/pdf。

我是否使用了错误的函数从文件中获取 PDF 内容?或者我设置的正文内容错误?我调用的 API 的文档指出 PDF 内容应发布在正文中,但没有提及将其作为参数发布。它还说在标题中设置 content-type: application/pdf ,我已经这样做了。但它没有说什么,但我认为这应该是一个简单的调用,但也许我只是对 cURL 不够了解......

has*_*dic 6

假设您使用的是 PHP 5.5+,您需要使用CURLfile来上传文件:

$file = new CURLFile('C:\MyFile.pdf','application/pdf','MyFile');
// your CURL here
curl_setopt($curl, CURLOPT_POSTFIELDS, ['pdf' => $file]);
...
Run Code Online (Sandbox Code Playgroud)

如果您使用的是旧版本,也许您应该尝试在文件名前面添加“@”,如下所示

curl_setopt($curl, CURLOPT_POSTFIELDS, array('name' => 'pdf', 'file' => '@C:\MyFile.pdf'); 
Run Code Online (Sandbox Code Playgroud)