Jquery File Upload Not Working Over 10 Mg
File upload is an essential aspect of any project. Given this importance, it is surprising that many developers face challenges of adding file upload characteristic to their projects. In particular, developers are unsure nigh how to upload and validate files.
In this tutorial, I will talk over how to implement Laravel file upload functionality with multiple file and paradigm uploading option. I will use the Laravel storage folder and then create database tape for uploading files. I will use Laravel 5.5 and Bootstrap to power the code of this tutorial.
- Prerequisites
- Create Model with Migration
- Item Model
- Create the Migration
- Model Of ItemDetails
- Migration of ItemDetails Table
- Database Configuration
- Set the Route
- Create the Controller
- View File (Upload_form.blade.php)
- Controller with Validation
- Storing Data and Files in Laravel
- With Validation
- Difference Between Local and Public Disks
- Manipulating files
- Sending Files as E-mail Attachments
- Create email sender class
- Create the electronic mail template
You might likewise like: PHP File Upload with jQuery AJAX
Prerequisites
For the purpose of this tutorial, I assume that you lot take a Laravel awarding installed on a web server. My setup is:
- Linux/Unix or WAMP/XAMPP surround
- Laravel v.5
- PHP 7.1
- MySQL
- Web server (Apache, NGINX or integrated PHP web server for testing)
I have installed a Laravel app on a Cloudways managed Laravel server because it has everything I'll demand for this tutorial. If you do non have an account on Cloudways, sign upwards for costless, and check out the following GIF to setup the server and application in just a few clicks.
Create Model with Migration
I will start by creating the model and the tables in which I will save the files.
Launch the SSH terminal, get to the awarding's public root folder and type following commands:
php artisan make:model Item -m php artisan make:model ItemDetails -m
Item Model
When the migration and the model take been created successfully, become to app/Item.php and add the following Model code to it:
<?php namespace App; utilize Illuminate\Database\Eloquent\Model; class Item extends Model { protected $fillable = ['proper name']; }
Create the Migration
Go to the database/migration folder and open the migration file for detail. You volition see the default structure that include (in my instance) id , name, timestamps.
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Pattern; use Illuminate\Database\Migrations\Migration; grade CreateItemsTable extends Migration { public role upward() { Schema::create('items', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->timestamps(); }); } public function down() { Schema::drop('items'); } }?>
Model Of ItemDetails
The model comprises of the following code:
<?php namespace App; use Illuminate\Database\Eloquent\Model; form ItemDetail extends Model { protected $fillable = ['item_id', 'filename']; public function detail() { return $this->belongsTo('App\Item'); } } ?>
In the above code, I used belongTO because itemDetails belongs to Particular table and item_id is the foreign key. This is known as inverse relation in Laravel.
Migration of ItemDetails Table
Go to the database/migration folder and open the migration file for itemdetails. You lot volition encounter the default construction that include id , name . timestamps.
<?php employ Illuminate\Support\Facades\Schema; apply Illuminate\Database\Schema\Blueprint; utilize Illuminate\Database\Migrations\Migration; class CreateItemDetailsTable extends Migration { /** * Run the migrations. * * @return void */ public office upward() { Schema::create('item_details', function (Pattern $table) { $table->increments('id'); $table->integer('item_id')->unsigned(); $tabular array->foreign('item_id')->references('id')->on('items'); $tabular array->string('filename'); $table->timestamps(); }); } public function downwardly() { Schema::drop('item_details'); } } ?>
Next , In the app/Providers/AppServiceProvider.php file, the boot method set a default cord length:
use Illuminate\Support\Facades\Schema; public function boot() { Schema::defaultStringLength(191); }
Database Configuration
In a Laravel powered app, database configuration is handled by two files: env and config/database.php. In my case, I created a database with the name uploading. The Cloudways Database Manager makes the entire process very like shooting fish in a barrel.
Next, run the post-obit command in the concluding to create tables in the database:
php artisan migrate
At present, when you check the database, you lot volition see that the tables accept been created successfully.
Y'all might as well like: Connect Laravel with Firebase Real Time Database
Prepare the Route
Route sets the awarding URL and the controller method for this URL. Routes are located in route/web.php and contains the following lawmaking:
Road::get('/multiuploads', '[email protected]'); Route::mail service('/multiuploads', '[email protected]');
Finish Wasting Time on Servers
Cloudways handle server management for you so you tin can focus on creating great apps and keeping your clients happy.
Create the Controller
Next, create the Controller by using the post-obit command:
php artisan brand:controller UploadController
Adjacent, go to app/Http/Controller/UploadController and open the Controller file. Add the following code to it:
namespace App\Http\Controllers; utilise Illuminate\Http\Request; course UploadController extends Controller { public function uploadForm() { return view('upload_form'); } public office uploadSubmit(Asking $request) { // coding …. } }
View File (Upload_form.blade.php)
In the view file, I have used Bootstrap for styling the code, link stylesheet , jQuery, JavaScript files.
<!doctype html> <html lang="{{ app()->getLocale() }}"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=ane"> <title>Laravel Uploading</championship> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/three.iii.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/iii.three.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css"> <!-- Styles --> <style> .container { margin-acme:2%; } </style> </head> <body> @if (count($errors) > 0) <div form="alert alert-danger"> <ul> @foreach ($errors->all() as $fault) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <div grade="container"> <div grade="row"> <div grade="col-medico-ii"> <img src="/32114.svg" width="lxxx" /></div> <div class="col-dr.-viii"><h2>Laravel Multiple File Uploading With Bootstrap Grade</h2> </div> </div> <br> <div class="row"> <div class="col-md-3"></div> <div grade="col-md-6"> <grade action="/multiuploads" method="mail service" enctype="multipart/form-data"> {{ csrf_field() }} <div class="grade-group"> <label for="Product Name">Product Name</characterization> <input type="text" name="name" class="grade-control" placeholder="Production Name" > </div> <characterization for="Production Name">Product photos (can attach more one):</label> <br /> <input blazon="file" class="form-control" name="photos[]" multiple /> <br /><br /> <input blazon="submit" class="btn btn-primary" value="Upload" /> </form> </div> </div> </div> </body> </html>
Controller with Validation
I have apply Bootstrap classes for showing the warning for validation and apply Laravel Validation methods to validate the type of file. Utilise the post-obit code for the controller:
<?php namespace App\Http\Controllers; employ App\Item; use App\ItemDetail; employ Illuminate\Http\Request; form UploadController extends Controller { public function uploadForm() { return view('upload_form'); } public function uploadSubmit(Request $request) { $this->validate($request, [ 'proper noun' => 'required', 'photos'=>'required', ]); if($asking->hasFile('photos')) { $allowedfileExtension=['pdf','jpg','png','docx']; $files = $request->file('photos'); foreach($files equally $file){ $filename = $file->getClientOriginalName(); $extension = $file->getClientOriginalExtension(); $cheque=in_array($extension,$allowedfileExtension); //dd($check); if($check) { $items= Item::create($request->all()); foreach ($request->photos as $photo) { $filename = $photo->shop('photos'); ItemDetail::create([ 'item_id' => $items->id, 'filename' => $filename ]); } repeat "Upload Successfully"; } else { echo '<div grade="alarm alarm-warning"><strong>Alert!</potent> Sorry Only Upload png , jpg , md</div>'; } } } } }?>
Storing Data and Files in Laravel
Laravel provides a storage filesystem that stores all the data including files and images.
For this, Laravel provides config/filesystems.php, located in the config folder. In this file, y'all can specify the locations for your file storage.
return [ 'default' => 'local', 'disks' => [ 'local' => [ 'driver' => 'local', 'root' => storage_path('app'), ], // ...
Using the above lawmaking snippet, you could relieve the files in app/storage folder instead of the public binder. This is a good coding practice for storing data because this location is inaccessible from the browser. For the purpose of this tutorial, I take created a folder with the name photos in storage/app/.
When the run the app in the browser, yous will see the following screens:
With Validation
To come across the epitome and file upload in Laravel in action, bank check out the demo.
Difference Between Local and Public Disks
You can see the disks local and public divers in config/filesystems.php. Laravel uses the local deejay configuration by default. The underlying difference between local and public disk is that local disk is individual and can't be accessed from the browser, whereas the public deejay tin exist easily accessed from the browser.
Since the public deejay is in storage/app/public and Laravel's server root is in public, you need to link storage/app/public to Laravel's public folder. We can do by running php artisan storage:link.
Manipulating files
Laravel largely needs external help in resizing images, adding filters and other related operations. Adding these feature to the native environment of Laravel will just bloat the application since there isn't any installs needed. For that, we need a bundle chosen intervention/paradigm. Before above, nosotros take already installed this package, but still composer requires it for reference.
We don't need to register annihilation since Laravel can automatically discover packages. Read the following if you are using lesser version than Laravel 5.5.
To resize an image
$epitome = Paradigm::make(storage_path('app/public/contour.jpg'))->resize(300, 200);
Even Laravel'southward packages are fluent.
Sending Files as Email Attachments
For send files with attachments yous just paste the post-obit lawmaking in your controller according to input fields.
<?php ... ... public function uploadDocument(Asking $asking) { $title = $asking->file('name'); // Get the uploades file with name document $document = $request->file('document'); // Required validation $request->validate([ 'proper name' => 'required|max:255', 'document' => 'required' ]); // Check if uploaded file size was greater than // maximum allowed file size if ($certificate->getError() == 1) { $max_size = $document->getMaxFileSize() / 1024 / 1024; // Become size in Mb $mistake = 'The certificate size must exist less than ' . $max_size . 'Mb.'; return redirect()->dorsum()->with('flash_danger', $error); } $data = [ 'document' => $document ]; // If upload was successful // send the electronic mail $to_email = [electronic mail protected]; \Postal service::to($to_email)->transport(new \App\Mail\Upload($data)); return redirect()->back()->with('flash_success', 'Your document has been uploaded.'); }
Create email sender form
To send the email in Laravel, you need to create a separate class file. This class will have the functionality to prepare electronic mail and its body. Besides nosotros will attach the uploaded file as inline zipper.
Here is my email grade:
<?php #App\Postal service\Upload.php namespace App\Post; use Illuminate\Bus\Queueable; utilise Illuminate\Mail\Mailable; apply Illuminate\Queue\SerializesModels; grade Upload extends Mailable { use Queueable, SerializesModels; protected $data; /** * Create a new message instance. * * @return void */ public office __construct($data=[]) { $this->data = $data; } /** * Build the message. * * @return $this */ public function build() { render $this->view('emails/upload') ->subject('Document Upload') ->attach($this->information['document']->getRealPath(), [ 'every bit' => $this->information['document']->getClientOriginalName(), 'mime' => $this->data['document']->getClientMimeType(), ]); } }
The important functions used here are:
– getRealPath(): Get the temporary upload path – getClientOriginalName(): Get the name of uploaded file – getClientMimeType(): Get the mime blazon of uploaded file
Create the e-mail template
In the to a higher place step, our email course refers to the e-mail template as return $this->view('emails/upload'). So we volition create the email template at resources/views/emails/upload.blade.php
#resource/views/emails/upload.blade.php <p>Hi,</p> <p>Please download the fastened file.</p> <p>Thanks</p>
At present when you submit the form, your uploaded file volition be sent an e-mail zipper.
Share your opinion in the comment section. Annotate NOW
Share This Article
Customer Review at
"Cloudways hosting has 1 of the best customer service and hosting speed"
Sanjit C [Website Developer]
Pardeep Kumar
Pardeep is a PHP Community Managing director at Cloudways - A Managed PHP Hosting Platform. He love to work on Open source platform , Frameworks and working on new ideas. Yous tin can electronic mail him at [e-mail protected]
Source: https://www.cloudways.com/blog/laravel-multiple-files-images-upload/
0 Response to "Jquery File Upload Not Working Over 10 Mg"
Post a Comment