0

I am uploading a file to my API built on laravel. In my code below, the data is sent to the API. But how can i get the file that was uploaded to the API ?

Controller

$file = $request->file('imported-file');
        $name = $file->getClientOriginalName();
        $path ='/Users/desktop/Folder/laravelapp/public/Voice/';
        $client = new \GuzzleHttp\Client();
        $fileinfo = array(
            'message'          =>  'Testing content',
            'recipient'  =>  "102425",
        );

        $res = $client->request('POST', $url, [
            'multipart' => [
                [
                    'name'     => 'FileContents',
                    'contents' => file_get_contents($path . $name),
                    'filename' => $name
                ],
                [
                    'name'     => 'FileInfo',
                    'contents' => json_encode($fileinfo)
                ]
            ],
        ]);

API Controller

        if (!empty('FileInfo')) {
            return response()->json([
                'status' => 'error',
                'file_content' => $request->file('FileContents'),
                'media'=>$request->hasFile('FileContents'),
            ]);
        }

This is the response, i get "file":null,"file_content":{},"media":true

Why is the file content empty when media is showing true meaning there is a file ?

RoboPHP
  • 410
  • 4
  • 12

1 Answers1

0

There can be multiple reasons :

  • Check your content type. Sometimes we forget to specify multipart/form-data and the request is sent with generic application/x-form-urlencoded etc.
  • Secondly if you are using jQuery, then set :

contentType: false, processData: false, cache: false

This will help your form request no getting converted to string payload and not forcing ajax to set content type. try using FormData.

Update : Found similar answer in this post has detailed answer for this.

Mihir Bhende
  • 8,677
  • 1
  • 30
  • 37