PHP通过cURL发送本地文件

时间:2014-12-01 12:25:08

标签: php curl upload restful-architecture

我试图通过客户端卷曲应用程序发送本地文件。我发现了一些使用表单中文件的例子。就我而言,我没有表格,只有本地文件。

$fileName = $_SERVER["DOCUMENT_ROOT"]."/www/images/test.pdf";

if(!file_exists($fileName)) {
       $out['status'] = 'error';
       $out['message'] = 'File not found.';
       exit(json_encode($out));
}
$data = array('name' => 'Foo', 'file' => '@'.$fileName);

$cURL = curl_init("http://myapi/upload-images");
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURL, CURLOPT_POST, 1);
curl_setopt($cURL, CURLOPT_POSTFIELDS, $data);

$response = curl_exec($cURL);
$error = curl_error($cURL);
curl_close($cURL);

die($response);

有了这个,我没有错误,但在服务器中$ _POST和$ _SERVER数组是空的。

我试过了,这次在发送之前创建了一个Curl文件:

// Mime type of file 
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$finfo = finfo_file($finfo, $fileName);

$cFile = new CURLFile($fileName, $finfo, "file");

//var_dump($cFile);
//CURLFile Object
//(
//   [name] => C:/.../test.pdf
//   [mime] => application/pdf
//   [postname] => file
// )

$cURL = curl_init("http://myapi/upload-images");
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURL, CURLOPT_POST, true);
curl_setopt($cURL, CURLOPT_POSTFIELDS, 
array(
     'file' => $cFile
));

$response = curl_exec($cURL);
curl_close($cURL);

die($response);

相同的回应。 $ _FILES是空的。

1 个答案:

答案 0 :(得分:3)

最后我找到了问题的原因。包含文件数据的数组必须具有filedata和filename密钥。

我们可以在文件名之前传递'@'并使用完整路径,但不推荐使用此选项。

$data = array( "filedata" => '@'.$fileName, "filename" => basename($fileName));

在这种情况下,我添加了一个Curl对象:

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$finfo = finfo_file($finfo, $fileName);

$cFile = new CURLFile($fileName, $finfo, basename($fileName));

$data = array( "filedata" => $cFile, "filename" => $cFile->postname);

完整的代码是:

$fileName = $_SERVER["DOCUMENT_ROOT"]."/www/images/test.pdf";
$fileSize = filesize($fileName);

if(!file_exists($fileName)) {
    $out['status'] = 'error';
    $out['message'] = 'File not found.';
    exit(json_encode($out));
}

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$finfo = finfo_file($finfo, $fileName);

$cFile = new CURLFile($fileName, $finfo, basename($fileName));
$data = array( "filedata" => $cFile, "filename" => $cFile->postname);

$cURL = curl_init("http://myapi/upload-images")
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);

// This is not mandatory, but is a good practice.
curl_setopt($cURL, CURLOPT_HTTPHEADER,
    array(
        'Content-Type: multipart/form-data'
    )
);
curl_setopt($cURL, CURLOPT_POST, true);
curl_setopt($cURL, CURLOPT_POSTFIELDS, $data);
curl_setopt($cURL, CURLOPT_INFILESIZE, $fileSize);

$response = curl_exec($cURL);
curl_close($cURL);


die($response);