簡體   English   中英

使用CURL上傳文件並使用Laravel方法檢索

[英]Uploading File with CURL and Retrieving in Laravel Method

我正在嘗試使用cURL在基於Laravel構建的端點中發布數據。 在我接收數據的API控制器中,我可以接收除媒體文件以外的所有數據。 我使用$request->hasFile('file')檢查文件是否存在,但返回false。 我也嘗試使用$request->file('file')但它返回null。

當我使用$request->get('file') ,得到以下響應。

文件 “:{” 名 “:”/用戶/名/文件/路徑/公/媒體/ aaaah.wav”, “默”:空, “postname”:空}

在下面,我使用$headers[] = "Content-Type: application/json"; 將收件人從數組轉換為字符串。 任何人都可以幫助我了解為什么在我使用$request->hasFile('file')$request->file('file')時在Laravel方法中未收到cURL發布$request->file('file')嗎?

AppController的

public function postCurlData()
{
   $endPoint = 'http://127.0.0.1:9000/api';          
   $apiKey = '****';
   $url = $endPoint . '?key=' . $apiKey;
   $dir = '/Users/name/File/path/app/public/media/test.wav'; // full directory of the file
   $curlFile = curl_file_create($dir);

    $data = [
       'recipient' => ['44909090', '44909090'],
       'content' => 'i love to code',
       'file' => $curlFile,          
     ];

    $ch = curl_init();
    $headers = array();
    $headers[] = "Content-Type: application/json";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    $result = curl_exec($ch);
    $result = json_decode($result, TRUE);
    curl_close($ch);
}

我正在接收數據的端點:

APIController

public function receiveCurlData()   
{   
    $apiKey = $request->get('key');
    if (($apiKey)) {
        return response()->json([
            'status' => 'success',
            'content' => $request->get('content'),
            'recipient' => $request->get('recipient'),
            'file' => $request->hasFile('file')                 
        ]);
    }
}

響應

{"status":"success","content":"I love to code","recipient":
["44909090","44909090"],"file":false}

這個答案與您的問題有關: 如何使用curl和php上傳文件

你應該刪除

 $headers = array();
    $headers[] = "Content-Type: application/json";

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

並刪除json_encode(),將其替換為普通數組

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $result = curl_exec($ch);
    $result = json_decode($result, TRUE);
    curl_close($ch);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM