使用php中的curl发送文件和表单字段时出错

时间:2014-02-05 11:44:31

标签: curl

我正在尝试使用PHP中的CURL发送一些表单字段和多个文件,得到以下错误。

"Required Multipartfile parameter utterance is not present". 

Below listed is the piece of code, I have used in my application.

$a1614_1 = "@" .realpath("RecordFiles/1614_1.wav");


$payload = array("sessionid"=>$sessionid,"clientid"=> $clientid,"userid"=>$userid,"utterance"=> $a1614_1,"type"=>$type,"action"=>$action);

$multipart_boundary = "ABC1234";

$request_headers    = array();
$request_headers[]  = "Content-Type: multipart/form-data; boundary=". $multipart_boundary;

$curl_options = array(
CURLOPT_URL => $base_api_url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query( $payload),
CURLOPT_HTTP_VERSION  => 1.0,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_VERBOSE => true,
CURLOPT_HTTPHEADER => $request_headers
);

$curl = curl_init();
curl_setopt_array( $curl, $curl_options );
$result = curl_exec( $curl );
curl_close ($curl);

In my code i'm passing utterance as one of the multipart parameter but still i'm getting the same error. I have googled to resolve the problem but not able to fix it. Is there any problem in the above code approach, if any one have idea please share to me to fix or resolve the issue.

请帮助/协助我解决此问题。

1 个答案:

答案 0 :(得分:3)

您正在尝试手动执行curl应该执行的操作(构建http查询,生成边界,添加标头,内容长度)。 顺便说一句,对于PHP 5.5+,您应该使用CURLFile而不是'@file'。

PHP代码低于5.5:

$a1614_1 = "@" .realpath("RecordFiles/1614_1.wav");

$payload = array("sessionid"=>$sessionid,"clientid"=> $clientid,"userid"=>$userid,"utterance"=> $a1614_1,"type"=>$type,"action"=>$action);

$curl_options = array(
CURLOPT_URL => $base_api_url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_HTTP_VERSION  => 1.0,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_VERBOSE => true
);

$curl = curl_init();
curl_setopt_array( $curl, $curl_options );
$result = curl_exec( $curl );
curl_close ($curl);

PHP 5.5 +代码:

$baseApiUrl = 'http://some.net/api';
$file = new CurlFile(realpath('RecordFiles/1614_1.wav'));

$fields = array(
    'sessionid' => $sessionid,
    'clientid' => $clientid,
    'userid' => $userid,
    'utterance' => $file,
    'type' => $type,
    'action' => $action
);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $baseApiUrl);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $fields);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($curl);

curl_close($curl);