简体   繁体   中英

Uploading File with CURL and Retrieving in Laravel Method

I'm trying to get data posted using cURL in my endpoint, which is built on Laravel. In my API controller, where I receive data, I am able to receive all the data except my media file. I check for presence of the file using $request->hasFile('file') but it returns false. I also try to get the file using $request->file('file') but it returns null.

When I use $request->get('file') , I get the following response.

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

Below, I am using $headers[] = "Content-Type: application/json"; to convert the recipient from array to string. Can anyone help me understand why the file posted by cURL is not being received in my Laravel method when I use $request->hasFile('file') and $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);
}

My endpoint where I'm receiving data:

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')                 
        ]);
    }
}

Response

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

This answer is related to your question: how to upload file using curl with php .

You should delete

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

And

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

And also delete the json_encode() replacing it by the plain array

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM