Input file in laravel 5.2?

2020-08-23 07:59发布

问题:

I'm trying to upload a file, but it fails when the request lands to the controller. With fails i mean that if i try $request->hasFile("filename") always returns false.

Is there some specific field that I have to specify in the view?

This is a snippet of the view:

<body>
    <form action="{{url('dev/tester')}}" method="POST">
        {{csrf_field()}}
        <input type="file" name="file">
        <button type="submit">Test</button>
    </form>
</body>

And here is the controller

class Tester extends Controller
{
    public function index(Request $request)
    {
        if($request->hasFile('file'))
        {
            dd('Got the file');
        }

        dd('No file');
    }

    public function testView()
    {
        return view('tests.file_upload');
    }
}

I always get returned 'No file'.

Any clue? I've even check the php.ini to see if there was a size limitation but it's all set to 32M as MAMP's pro default settings...

回答1:

Check if you may have forgotten to add enctype="multipart/form-data" in form



回答2:

You must enabling upload form to your form,

there is 2 ways to do it :

  1. By using HTML

    <form action="{{url('dev/tester')}}" method="post" enctype="multipart/form-data">
    
  2. By using laravel Form & HTML (https://laravelcollective.com/docs/5.2/html)

    {!! Form::open( [ 'action' => url( 'dev/tester' ), 'method' => 'post', 'files' => true ] ) !!}
        // Your form
    {!! Form::close() !!}
    

This should work like a charm!



回答3:

Try adding the enctype="multipart/from-data" to your form, then it should work!