通过PHP curl将文件上传到api时,内容长度问题。

问题描述 投票:0回答:1

我正在使用以下代码通过api上传文件。 但我发现上传后文件内容类型错误(大约26个字节)。 内容类型将为$ data_string的长度。 我试图将内容长度更改为上传文件的文件大小。 但是之后,api无法正常工作。 我编码有误吗?

$data        = array("Content" => "file.wav"); //around 4mb
$data_string = json_encode($data);  
$ch          = curl_init();

curl_setopt($ch, CURLOPT_URL, 'URL');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);   
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                        
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
  'Content-type: audio/wav',                                                                           
  'Content-Length: ' . strlen($data_string))                                                                       
);                      
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");

$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$data        = curl_exec($ch);

curl_close($ch);
php api curl
1个回答
0
投票

$ data_string是由json编码的数组形成的字符串,该数组具有一对字符串,因此它将是该数组的大小而不是文件的大小。 我建议您在尝试查找文件大小时使用filesize()函数。

http://www.php.net//manual/zh/function.filesize.php

*如果格式正确,还请检查“ $ username:$ password”。

© www.soinside.com 2019 - 2024. All rights reserved.