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

时间:2016-02-05 17:04:17

标签: php pdf curl

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

现有的实现只有POST并接收JSON数据,因此非常简单。当我尝试将代码更改为POST application / pdf content到另一个端点时,我不断收到以下错误:

文件类型错误。可接受的内容类型是application / pdf,text / richtext,text / plain,image / 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);  

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

我是否使用错误的功能从文件中获取PDF内容?还是我设置了身体内容错误?我调用的API有文档说明PDF内容应该发布在正文中,没有提到将其作为参数发布。它还说要在标题中设置content-type:application / pdf,我已经完成了。但它没有说什么,但我认为这应该是一个简单的电话,但也许我只是对cURL不够了解...

1 个答案:

答案 0 :(得分:2)

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

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

如果您使用的是旧版本,也许您应该尝试在建议here的文件名前添加“@”:

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