In this PHP Laravel Tutorial, I will tell you how to upload multiple images with preview using dropzone.js with example.
There are many plugins available to upload multiple images with preview. Dropzone provides the easiest way to upload multiple files with best user interface.
Dropzone is an open source and light weight JavaScript library that provides the drag and drop features to upload images with preview images.
Dropzone does not handle the server side script so you will have to write your own code to save file in a specific path.
There are filter options with dropzone such as you can set validation for max upload or apply restriction to upload only image file or have any other file extension.
For this example, you will need the dropzone library :
- dropzone.css
- dropzone.js
In this first step, We will add two following routes :
routes/web.php
- Route::get('dropzoneFile','HomeController@dropzoneFile') ;
- Route::post('dropzoneUploadFile',array('as'=>'dropzone.uploadfile','uses'=>'HomeController@dropzoneUploadFile')) ;
First route is used to render view file and second routes is used to save file uploaded with dropzone plugin.
Step 2: HomeController with two MethodIn this step, We will create HomeController file in following path app/Http/Controllers/ and define two method in following way :
app/Http/Controllers/HomeController.php
- <?php
- namespace App\Http\Controllers;
- use App\Http\Requests;
- use Illuminate\Http\Request;
- class HomeController extends Controller
- {
- public function dropzoneFile(){
- return view('dropzone_file_upload');
- }
- public function dropzoneUploadFile(Request $request){
- $imageName = time().'.'.$request->file->getClientOriginalExtension();
- $request->file->move(public_path('images'), $imageName);
- return response()->json(['success'=>$imageName]);
- }
- }
Now create a folder "images" in public directory to store all files.
Step 3: Add Blade FileIn this last step, We will create a view file "dropzone_file_upload.blade.php" in following path resources/views/.
resources/views/dropzone_file_upload.blade.php
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <title>Laravel: upload multiple file using drag and drop feature</title>
- <link href="http://demo.expertphp.in/css/dropzone.css" rel="stylesheet">
- <script src="http://demo.expertphp.in/js/dropzone.js"></script>
- </head>
- <body>
- <h3>Laravel 5.4 : Upload multiple file using dropzone</h3>
- {!! Form::open([ 'route' => [ 'dropzone.uploadfile' ], 'files' => true, 'class' => 'dropzone','id'=>"image-upload"]) !!}
- {!! Form::close() !!}
- </body>
- </html>
You can set the validation option with dropzone in following way :
- <script type="text/javascript">
- Dropzone.options.imageUpload = {
- maxFilesize : 1,
- acceptedFiles: ".jpeg,.jpg,.png,.gif"
- };
- </script>