Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 853
hendraspt Avatar asked Apr 19 '16 10:04

hendraspt


1 Answers

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.

like image 55
Mustafa Ehsan Alokozay Avatar answered Oct 19 '22 23:10

Mustafa Ehsan Alokozay