hendraspt hendraspt - 8 months ago 116
HTTP Question

Upload pdf file using Laravel 5

I'm using Laravel 5.2 and I want to make a form which can upload a pdf file with it. I want to add that file on folder "files" in "public" folder.

here is my view:

<div class="form-group">
<label for="upload_file" class="control-label col-sm-3">Upload File</label>
<div class="col-sm-9">
<input class="form-control" type="file" name="upload_file" id="upload_file">
</div>
</div>


and what should I do next? what should I add in my controller and route?

Answer Source

First you should add enctype="multipart/form-data" to your <form> tag. Then in your controller handle the file upload as follow:

class FileController extends Controller
{
    // ...

    public function upload(Request $request)
    {
        $uniqueFileName = uniqid() . $request->get('upload_file')->getClientOriginalName() . '.' . $request->get('upload_file')->getClientOriginalExtension());

        $request->get('upload_file')->move(public_path('files') . $uniqueFileName);

        return redirect()->back()->with('success', 'File uploaded successfully.');
    }

    // ...
}

Link to Laravel Docs for Handling File Uploads

Laravel casts the file type params in request to UploadedFile objects. You can see Symfony's UploadedFile class here for available methods and attributes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download