Laravel $ request-> file () returns null

There is a problem downloading files using Laravel on the back-end.

Question

The Laravel $request->file() method returns null.

Customization

I am creating an AJAX request using superagent , debugging the request and everything seems fine. Content-Length changes depending on the image being added, indicating that the image has been added to the request. The Content-Type parameter is also set to multipart/form-data .

 // request headers Content-Length:978599 Content-Type:multipart/form-data; // request payload Content-Disposition: form-data; name="files"; filename="item-keymoment.png" Content-Type: image/png 

But I can not get the file in Laravel. Using $request->file('files') returns NULL , but if I debug the $_FILES , I noticed that my file was uploaded.

 dd($request->file('files')) // NULL dd($_FILES); // array:1 [ // "files" => array:5 [ // "name" => "item-keymoment.png" // "type" => "image/png" // "tmp_name" => "/tmp/phpipbeeM" // "error" => 0 // "size" => 978274 // ] // ] dd($request->files->all()) // [] 

What can cause Laravel to ignore the file?
Content-Type input file is not application/octet-stream ?

Below are the answers to the question.

+5
source share
2 answers

It is noted that the $request object that I received in the Controller method was an instance of JsonRequest , which is a regular class (empty at the moment) that extends Illuminate\Http\Request .

And it is implemented as:

 <?php namespace App\Http\Requests; use Illuminate\Http\Request; class JsonRequest extends Request { } 

But if I change:

 // from use App\Http\Requests\JsonRequest; public function add_background_image (JsonRequest $request) { dd($request->file('files')) // NULL } // to use Illuminate\Http\Request; public function add_background_image (Request $request) { dd($request->file('files')) // UploadedFile {#266 // -test: false // -originalName: "item-keymoment.png" // -mimeType: "image/png" // -size: 978274 // -error: 0 // ... // } } 

I get the desired input file. Now switching instance of $request solves my problem

But I don’t understand why / how the Illuminate\Http\Request extension with an empty class breaks things.
Can someone explain?

My intention with the Illuminate\Http\Request subclass was to be able to attach methods to $requests to uniformly handle exceptions / errors for API requests. For example, when the deployment displays exception messages but returns a fixed message in production.
Are there any different / better / more Laravel ways to do this?
I think it will just create a JsonController instead of continuing with the request.

+1
source

You must add 'enctype = "multipart / form-data' to the form tag

For instance:

 <form method="POST" action="{{route('back.post.new')}}" enctype="multipart/form-data"> ...... </form> 

By adding it, you can use your custom query.

Hope this helps you!

+1
source

All Articles