如何使用Php Curl无输入类型文件控制发送文件进行上传?

时间:2016-07-30 11:46:57

标签: php curl

我想在不使用文件控件和使用Curl Request ..

的情况下将文件从一台服务器上传到另一台服务器
curl -X POST --header 'Content-Type: multipart/form-data' --header 'Accept: application/json' --header 'api-token: 6a53bcbe222c490196e4b9f87ba9148c' --header 'api-secret: 6a53bcbe222c490196e4b9f87ba9148c' -F "document[]=@C:/xampp/htdocs/project/image_name.ext" -F "document[]=@C:/xampp/htdocs/project/image_name.ext" -F "document[]=@C:/xampp/htdocs/project/image_name.ext" 'https://server_api_url.com

' 上面的卷曲效果很好......

但我不知道如何在php中发布文件... 下面是我使用php curl发送帖子数据的示例代码

    <?php

       $doc_file_path_string = ' -F document[]=@image_name';
       array_push($doc_data_array, $doc_file_path_string);    


       $url = 'https://server_url.com'; 
       $ch = curl_init();
       curl_setopt($ch, CURLOPT_URL,$url);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
       curl_setopt($ch, CURLOPT_POST, 1);
       curl_setopt($ch, CURLOPT_POSTFIELDS, implode(' ',$doc_data_array));
       $headers = array();
       $headers[] = "Content-Type: multipart/form-data";
       $headers[] = "Accept: application/json";
       $headers[] = "Api-Token: api_key";
       $headers[] = "Api-Secret: api_key ";
       curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
       echo $result = curl_exec($ch); 
    ?> 

1 个答案:

答案 0 :(得分:0)

以下是我的表现

$url = <some url>;
$ch = curl_init();
$headers = ["Content-Type:multipart/form-data"];

// Define curl options
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);

// Here we make base64 encode for file content and push it into curl           
$base64 = base64_encode(file_get_contents(<path to file>));
curl_setopt($ch, CURLOPT_POSTFIELDS, ['file' => $base64]);

// Make request
$response = curl_exec($ch);
curl_close($ch);