1

大家好!我有 curl 命令(音频文件上传):

curl -k -v -H "Expect: " -H "Content-Type:application/octet-stream" --data-binary  '@/Path/To/File/test.wav' -X POST  'https://myapi.com?param1=xxx&param2=yyy'

文件已成功上传且可读。但是当我使用 php 脚本时:

$filename = 'test.wav';
$file = '@/Path/To/File/test.wav';

$post_url = "https://someapi.com?param1=xxx&param2=yyy";
$post_str = array("$filename" => $file);

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/octet-stream'));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect: '));
curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_str);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$http_body = curl_exec($ch);
var_dump($http_body);

文件成功上传并且 test.wav 无效(有一些错误)。我在脚本中做错了什么?

4

2 回答 2

3

我怀疑问题出在以下几行:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/octet-stream'));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect: '));

第二次调用将删除“Content-Type”标头。尝试合并这些:

$headers = array('Content-Type:application/octet-stream','Expect: ');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
于 2013-05-30T14:56:00.340 回答
0
$filename = 'test.wav';
$file = '/Path/To/File/test.wav';

$post_url = "https://someapi.com?param1=xxx&param2=yyy";
$post_str = file_get_contents($file);
$headers = array('Content-Type:application/octet-stream', 'Expect: ');

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_str);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch,CURLOPT_VERBOSE,true); 
curl_setopt($ch, CURLOPT_STDERR, fopen("/Path/to/header.txt", "w+"));
$http_body = curl_exec($ch);

这是完美的工作。我自己解决了这个问题。文件上传到服务器二进制文件。谢谢你们!

于 2013-05-31T11:55:15.297 回答