2014-12-01 2 views
3

클라이언트 컬 응용 프로그램에서 로컬 파일을 보내려고합니다. 양식에서 파일을 사용하여 몇 가지 예를 발견했습니다. 제 경우에는 양식이 없지만 로컬 파일이 있습니다.PHP cURL로 로컬 파일 보내기

$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); 

이렇게하면 서버에 erros가 없지만 $ _POST 및 $ _SERVER 배열은 비어 있습니다.

// 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은 비어 있습니다.

+0

http://stackoverflow.com/questions/15200632/how-to- upload-file-using-curl-with-php –

+0

@StrawHat에 감사드립니다. 내 첫 번째 경우에는 realpath()를 추가하여 시도했다. 동일한 응답, $ _FILES는 서버에서 비어 있습니다. – Dreyfi

답변

3

마지막으로 문제의 원인을 발견했습니다. 파일 데이터가있는 배열에는 파일 이름과 파일 이름 키가 있어야합니다.

전체 경로와 함께 파일 이름 앞에 '@'를 전달할 수 있지만 더 이상 사용되지 않습니다.

$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); 

전체 코드는 다음과 같습니다 :이 경우

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

가 나는 컬 객체를 추가

$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); 
관련 문제