【问题标题】:Uploading File with CURL and Retrieving in Laravel Method使用 CURL 上传文件并在 Laravel 方法中检索
【发布时间】:2019-06-09 09:02:29
【问题描述】:

我正在尝试在基于 Laravel 的端点中使用 cURL 获取发布的数据。在我接收数据的 API 控制器中,我能够接收除媒体文件之外的所有数据。我使用$request->hasFile('file') 检查文件是否存在,但它返回false。我也尝试使用$request->file('file') 获取文件,但它返回 null。

当我使用$request->get('file') 时,我得到以下响应。

file":{"name":"/Users/name/File/path/public/media/aaaah.wav","mime":null,"postname":null}

下面,我使用$headers[] = "Content-Type: application/json"; 将接收者从数组转换为字符串。当我使用 $request->hasFile('file')$request->file('file') 时,任何人都可以帮助我理解为什么我的 Laravel 方法没有收到 cURL 发布的文件吗?

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}

【问题讨论】:

    标签: php laravel curl laravel-request


    【解决方案1】:

    此答案与您的问题有关: how to upload file using curl with 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);
    

    【讨论】:

      猜你喜欢
      • 2019-02-15
      • 1970-01-01
      • 2015-05-14
      • 1970-01-01
      • 2020-04-06
      • 2020-09-25
      • 2023-03-29
      • 2018-06-15
      • 2013-03-15
      相关资源
      最近更新 更多