Upload pdf file using Laravel 5

46,797

Solution 1

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.

Solution 2

First of all, the documentation tells you exactly what to do here.

What you want to do is adding this to your <form> tag: enctype="multipart/form-data" (This allows you to upload data), set a method(get/post) and an action (url).

Then you want to set up your routes.

For example: Route::post('/pdf/upload', 'FileController@upload');

This way you make sure that when you send the form it will go to your FileController with upload as function.

In your controller you want to declare the file as explained in the docs.
$file = $request->file('photo');.

From this point you can do whatever you'd like to do with the file ($file). For example uploading it to your own server.

Solution 3

  public function store(Request $request)
  {
        if($request->file('file')) 
        {
            $file = $request->file('file');
            $filename = time() . '.' . $request->file('file')->extension();
            $filePath = public_path() . '/files/uploads/';
            $file->move($filePath, $filename);
        }
  }

Solution 4

You Could Use Simple Method It Can Save The File

$path = $request->file('avatar')->store('avatars');

For More Information Here

Solution 5

you can this code for upload file in Laravel:

 $request->file('upload_file')->move($path,$name);
Share:
46,797
hendraspt
Author by

hendraspt

Updated on February 03, 2020

Comments

  • hendraspt
    hendraspt over 4 years

    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?