下载&使用cURL上传文件

时间:2018-01-19 00:45:35

标签: php curl

我一直在尝试使用cURL与api进行交互,我想用这个代码段下载一个文件,但它所做的就是在浏览器中打开文件,第二个代码段应该上传一个pdf文件使用cURL的多部分表单数据,但它给我的全部是;

“{”type“:”request_error“,”detail“:”多部分表单解析错误 - 多部分中的无效边界:无“}”

错误,我已经尝试用邮递员执行该操作,它在那里运行良好,当我复制并粘贴相同的代码时,它仍然给我与上面相同的错误,欢呼,提前谢谢。

这是代码;

下载代码段

    $id = "rZFbMKmj2zZbMUbp5KrjCH";

    $auth = $this->access_token;
    $curl = curl_init( PANDA_APIURL . "/documents/".$id."/download");

    //$fp = fopen('Test.pdf', 'w+');
    curl_setopt_array($curl, array(
      CURLOPT_URL => PANDA_APIURL . "/documents/".$id."/download",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 50,
      CURLOPT_TIMEOUT => 300,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      //CURLOPT_FILE => $fp,
      CURLOPT_CUSTOMREQUEST => "GET",
      CURLOPT_HTTPHEADER => array(
        "Authorization: Bearer $auth"
      ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);
    //fclose($fp);

    if ($err) {
      echo "cURL Error #:" . $err;
    } else {
      echo $response;
    }

使用multipart表格数据片段上传文件;

    $auth = $this->access_token;
    $boundary = '7aBMjcE3CIYntqQ3';
    $curl = curl_init();

      curl_setopt_array($curl, array(
      CURLOPT_URL => PANDA_APIURL . "/documents",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => '------WebKitFormBoundary7aBMjcE3CIYntqQ3
      Content-Disposition: form-data; name="file"; filename="samplepdf.pdf" 
      Content-Type: application/pdf 


      ------WebKitFormBoundary7aBMjcE3CIYntqQ3
      Content-Disposition: form-data; name="data"

      {  
         "name": "Pdf Doc",    
         "recipients": [  
         {  
             "email": "xyz@gmail.com",
             "first_name": "Jane",
             "last_name": "Roe"   
         }  
        ],
        "fields": {    
            "name": {  
            "value": "John"       
            },
            "like": {  
            "value": true
            }
        }
      }
      ------WebKitFormBoundary7aBMjcE3CIYntqQ3',
      CURLOPT_HTTPHEADER => array(
        "Authorization: Bearer $auth",
        "Content-Type: multipart/form-data;----WebKitFormBoundary'.$boundary"

      ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
      echo "cURL Error #:" . $err;
    } else {
      echo $response;
    }

0 个答案:

没有答案