laravel The file download.jpg was not uploaded due to an unknown error.
File upload is an essential attribute of whatever project. Given this importance, information technology is surprising that many developers face challenges of calculation file upload feature to their projects. In particular, developers are unsure nigh how to upload and validate files.
In this tutorial, I will discuss how to implement Laravel file upload functionality with multiple file and image uploading option. I volition use the Laravel storage binder and and then create database tape for uploading files. I will use Laravel 5.5 and Bootstrap to ability the lawmaking of this tutorial.
- Prerequisites
- Create Model with Migration
- Detail Model
- Create the Migration
- Model Of ItemDetails
- Migration of ItemDetails Table
- Database Configuration
- Prepare the Road
- Create the Controller
- View File (Upload_form.blade.php)
- Controller with Validation
- Storing Information and Files in Laravel
- With Validation
- Difference Between Local and Public Disks
- Manipulating files
- Sending Files as Email Attachments
- Create email sender class
- Create the email template
You lot might also similar: PHP File Upload with jQuery AJAX
Prerequisites
For the purpose of this tutorial, I assume that you have a Laravel application installed on a web server. My setup is:
- Linux/Unix or WAMP/XAMPP environment
- Laravel five.v
- PHP seven.one
- 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 information technology has everything I'll demand for this tutorial. If you exercise not take an account on Cloudways, sign up for free, and check out the following GIF to setup the server and application in only 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 application's public root folder and blazon following commands:
php artisan make:model Item -m php artisan make:model ItemDetails -k
Particular Model
When the migration and the model have been created successfully, get to app/Item.php and add together the following Model code to it:
<?php namespace App; use Illuminate\Database\Eloquent\Model; grade Item extends Model { protected $fillable = ['name']; }
Create the Migration
Get to the database/migration folder and open the migration file for particular. Y'all will see the default construction that include (in my case) id , name, timestamps.
<?php utilize Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; form CreateItemsTable extends Migration { public function up() { Schema::create('items', function (Blueprint $table) { $table->increments('id'); $table->cord('proper noun'); $table->timestamps(); }); } public function down() { Schema::drop('items'); } }?>
Model Of ItemDetails
The model comprises of the post-obit code:
<?php namespace App; use Illuminate\Database\Eloquent\Model; class ItemDetail extends Model { protected $fillable = ['item_id', 'filename']; public part item() { render $this->belongsTo('App\Item'); } } ?>
In the higher up code, I used belongTO because itemDetails belongs to Item table and item_id is the foreign key. This is known as changed relation in Laravel.
Migration of ItemDetails Table
Go to the database/migration folder and open the migration file for itemdetails. Yous will meet the default structure that include id , proper noun . timestamps.
<?php utilise Illuminate\Back up\Facades\Schema; utilize Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateItemDetailsTable extends Migration { /** * Run the migrations. * * @render void */ public part upwardly() { Schema::create('item_details', function (Pattern $table) { $table->increments('id'); $table->integer('item_id')->unsigned(); $table->foreign('item_id')->references('id')->on('items'); $table->string('filename'); $table->timestamps(); }); } public function downward() { 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 ii files: env and config/database.php. In my case, I created a database with the proper noun uploading. The Cloudways Database Manager makes the entire process very easy.
Next, run the following command in the terminal to create tables in the database:
php artisan migrate
Now, when you lot check the database, you will see that the tables accept been created successfully.
You might besides like: Connect Laravel with Firebase Real Time Database
Gear up upward the Route
Route sets the application URL and the controller method for this URL. Routes are located in route/web.php and contains the following code:
Road::get('/multiuploads', '[email protected]'); Route::post('/multiuploads', '[email protected]');
Stop Wasting Time on Servers
Cloudways handle server management for you and so you 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 make:controller UploadController
Next, go to app/Http/Controller/UploadController and open the Controller file. Add the post-obit code to it:
namespace App\Http\Controllers; use Illuminate\Http\Request; grade UploadController extends Controller { public function uploadForm() { return view('upload_form'); } public function uploadSubmit(Request $request) { // coding …. } }
View File (Upload_form.blade.php)
In the view file, I accept used Bootstrap for styling the lawmaking, link stylesheet , jQuery, JavaScript files.
<!doctype html> <html lang="{{ app()->getLocale() }}"> <head> <meta charset="utf-8"> <meta http-equiv="10-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=one"> <title>Laravel Uploading</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.three.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="bearding"> <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css"> <!-- Styles --> <fashion> .container { margin-superlative:2%; } </style> </head> <body> @if (count($errors) > 0) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <div course="container"> <div class="row"> <div class="col-medico-2"> <img src="/32114.svg" width="80" /></div> <div class="col-doctor-8"><h2>Laravel Multiple File Uploading With Bootstrap Form</h2> </div> </div> <br> <div class="row"> <div form="col-md-3"></div> <div class="col-doc-6"> <course action="/multiuploads" method="post" enctype="multipart/form-data"> {{ csrf_field() }} <div class="form-group"> <characterization for="Production Name">Production Proper noun</label> <input blazon="text" proper noun="name" class="class-control" placeholder="Product Proper name" > </div> <label for="Product Proper name">Product photos (tin can attach more than one):</label> <br /> <input type="file" class="form-control" name="photos[]" multiple /> <br /><br /> <input type="submit" class="btn btn-primary" value="Upload" /> </class> </div> </div> </div> </body> </html>
Controller with Validation
I have use Bootstrap classes for showing the alert for validation and use Laravel Validation methods to validate the type of file. Use the following code for the controller:
<?php namespace App\Http\Controllers; employ App\Item; use App\ItemDetail; use Illuminate\Http\Request; form UploadController extends Controller { public office uploadForm() { render view('upload_form'); } public role uploadSubmit(Request $request) { $this->validate($request, [ 'name' => 'required', 'photos'=>'required', ]); if($request->hasFile('photos')) { $allowedfileExtension=['pdf','jpg','png','docx']; $files = $request->file('photos'); foreach($files equally $file){ $filename = $file->getClientOriginalName(); $extension = $file->getClientOriginalExtension(); $check=in_array($extension,$allowedfileExtension); //dd($check); if($bank check) { $items= Item::create($request->all()); foreach ($asking->photos as $photo) { $filename = $photograph->store('photos'); ItemDetail::create([ 'item_id' => $items->id, 'filename' => $filename ]); } repeat "Upload Successfully"; } else { repeat '<div class="warning alert-warning"><strong>Warning!</strong> Sorry Only Upload png , jpg , doctor</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 binder. In this file, you tin specify the locations for your file storage.
return [ 'default' => 'local', 'disks' => [ 'local' => [ 'driver' => 'local', 'root' => storage_path('app'), ], // ...
Using the higher up code snippet, you could salve the files in app/storage folder instead of the public binder. This is a good coding practice for storing data considering this location is inaccessible from the browser. For the purpose of this tutorial, I have created a folder with the name photos in storage/app/.
When the run the app in the browser, y'all will see the following screens:
With Validation
To see the paradigm and file upload in Laravel in activity, check out the demo.
Difference Between Local and Public Disks
You can see the disks local and public defined in config/filesystems.php. Laravel uses the local disk configuration by default. The underlying divergence betwixt local and public disk is that local deejay is individual and can't be accessed from the browser, whereas the public disk tin be hands 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. Nosotros can practise past 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 but bloat the application since there isn't any installs needed. For that, we need a package called intervention/image. Earlier in a higher place, we accept already installed this packet, just still composer requires information technology for reference.
We don't demand to register annihilation since Laravel can automatically detect packages. Read the following if y'all are using lesser version than Laravel 5.v.
To resize an image
$prototype = Image::make(storage_path('app/public/profile.jpg'))->resize(300, 200);
Fifty-fifty Laravel's packages are fluent.
Sending Files as Email Attachments
For send files with attachments y'all just paste the following code in your controller according to input fields.
<?php ... ... public part uploadDocument(Asking $request) { $title = $request->file('proper noun'); // Get the uploades file with name document $document = $request->file('document'); // Required validation $asking->validate([ 'name' => 'required|max:255', 'certificate' => 'required' ]); // Check if uploaded file size was greater than // maximum allowed file size if ($document->getError() == 1) { $max_size = $document->getMaxFileSize() / 1024 / 1024; // Go size in Mb $fault = 'The document size must be less than ' . $max_size . 'Mb.'; return redirect()->back()->with('flash_danger', $error); } $data = [ 'certificate' => $document ]; // If upload was successful // ship the email $to_email = [email protected]; \Mail::to($to_email)->send(new \App\Mail service\Upload($data)); return redirect()->back()->with('flash_success', 'Your document has been uploaded.'); }
Create email sender class
To send the email in Laravel, you demand to create a separate class file. This class will accept the functionality to set up email and its trunk. Besides nosotros will adhere the uploaded file as inline zipper.
Here is my e-mail form:
<?php #App\Mail\Upload.php namespace App\Mail service; apply Illuminate\Bus\Queueable; apply Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; course Upload extends Mailable { use Queueable, SerializesModels; protected $information; /** * Create a new bulletin instance. * * @return void */ public role __construct($data=[]) { $this->data = $data; } /** * Build the bulletin. * * @render $this */ public role build() { return $this->view('emails/upload') ->discipline('Document Upload') ->adhere($this->information['certificate']->getRealPath(), [ 'as' => $this->data['certificate']->getClientOriginalName(), 'mime' => $this->data['document']->getClientMimeType(), ]); } }
The important functions used here are:
– getRealPath(): Get the temporary upload path – getClientOriginalName(): Go the proper name of uploaded file – getClientMimeType(): Get the mime blazon of uploaded file
Create the email template
In the higher up step, our email course refers to the electronic mail template as return $this->view('emails/upload'). So we will create the email template at resources/views/emails/upload.blade.php
#resources/views/emails/upload.blade.php <p>Howdy,</p> <p>Please download the fastened file.</p> <p>Thanks</p>
Now when y'all submit the form, your uploaded file will be sent an electronic mail attachment.
Share your opinion in the comment section. COMMENT Now
Share This Article
Client Review at
"Cloudways hosting has one of the best customer service and hosting speed"
Sanjit C [Website Programmer]
Pardeep Kumar
Pardeep is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. He beloved to work on Open source platform , Frameworks and working on new ideas. You tin can email him at [email protected]
Source: https://www.cloudways.com/blog/laravel-multiple-files-images-upload/
0 Response to "laravel The file download.jpg was not uploaded due to an unknown error."
Post a Comment