首页 > 解决方案 > 如何停止将“边界”插入“内容类型”字段的 PHP cURL 上传?

问题描述

我正在使用以下代码使用 PHP cURL 将 MP4 文件上传到 Web 服务。

我在 CURLOPT_HTTPHEADER 中将“Content-Type”指定为“video/mp4”。

不幸的是,上传文件后,在服务中为其存储的“Content-Type”显示为:“content_type”:“video/mp4;boundary=----WebKitFormBoundaryfjNZ5VkJS8z3CB9X”

如您所见,“边界”已插入“内容类型”。

然后当我下载文件时,它无法播放,并显示“文件不受支持/文件扩展名不正确/文件损坏”消息。

$authorization = "Authorization: Bearer [token]"; 

$args['file'] = curl_file_create('C:\example\example.mp4','video/mp4','example');

$url='[example web service URL]';

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data', 'Accept: application/vnd.mendeley-content-ticket.1+json', $authorization)); 
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS , $args);

$response = curl_exec($ch); // URL encoded output - needs to be URL encoded to get the HREF link header
curl_close($ch);

非常感谢任何帮助、建议或指点!

标签: phpweb-servicescurl

解决方案


也许 API 不需要 POST 多部分,而是正文本身的实际内容:

参考:如何在 PHP curl 中发布大量数据而没有内存开销?

您需要使用 PUT 方法将文件的实际内容放入正文 - 如果您使用 POST,它将尝试作为表单发送。

$authorization = "Authorization: Bearer [token]"; 
$file = 'C:\example\example.mp4';
$infile = fopen($file, 'r');

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,            "https://api.mendeley.com/file_contents");
curl_setopt($ch, CURLOPT_PUT,            1 ); // needed for file upload
curl_setopt($ch, CURLOPT_INFILESIZE,     filesize($file));
curl_setopt($ch, CURLOPT_INFILE,         $infile);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,  'POST' );
curl_setopt($ch, CURLOPT_POST,           1);
curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: video/mp4', 'Accept: application/vnd.mendeley-content-ticket.1+json', $authorization)); 

curl_setopt($ch, CURLOPT_HEADER,         0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$result=curl_exec ($ch);

推荐阅读