Single Image Upload in Vue Js Laravel
We will apply Laravel as a backend and Vue js equally a frontend framework or library.
Steps to upload file in Laravel Vue
In this minor projection, we volition upload an image from the vue component. Showtime, we download the Laravel so install the dependencies usingpm, and then we volition beginning our project.
The first footstep volition be to install and configure the Laravel Framework.
Step one: Install Laravel
Go to your terminal and hit the following command.
composer create-projection laravel/laravel vuefileupload --prefer-dist
Afterwards installation, go to the project binder root and type the following control.
npm install
It installs all the necessary dependencies to build Vue components.
Pace 2: Configure the database.
Add your database credentials in the.envfile.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=vueupload DB_USERNAME=root DB_PASSWORD=
Pace iii: Create a model and migration files.
To create both files, insert the post-obit command.
php artisan make:model FileUpload -1000
It generates both model and migration files.
Footstep 4: Define the schema in the migration file.
Get to thecreate_file_uploads_table.phpfile and add the schema to it.
Schema::create('file_uploads', office (Design $table) { $table->increments('id'); $table->string('image_name'); $table->timestamps(); }); Now, drift the table into the database.
php artisan migrate
Step 5: Define the routes in the web.php file.
Define the following route in the web.phpfile.
Route::mail service('/image/store', 'ImageController@store'); Also, create an ImageController.phpfile via the post-obit control.
php artisan make:controller ImageController
In that file, ascertain the store function.
<?php namespace App\Http\Controllers; use App\FileUpload; use Illuminate\Http\Request; class ImageController extends Controller { public role shop(Request $request) { } } Step half dozen: Create a Vue component to upload a file.
Get to theresource >> avails >> js >> componentsbinder and create a new file calledImageuploadComponent.vue.
// ImageuploadComponent.vue <template> <div form="container" id="app"> <div class="row justify-content-center"> <div class="col-md-8"> <div course="card bill of fare-default"> <div class="card-header">File Upload Component</div> <div class="card-body"> We need to write here file upload HTML code. </div> </div> </div> </div> </div> </template> <script> export default { } </script> Okay, and so nosotros have created a new component. Next step is to register that component into theresources >> assets >> js >> app.jsfile.
// app.js /** * First nosotros will load all of this project'due south JavaScript dependencies which * includes Vue and other libraries. Information technology is a great starting indicate when * building robust, powerful web applications using Vue and Laravel. */ require('./bootstrap'); window.Vue = require('vue'); /** * Next, we will create a fresh Vue awarding instance and attach it to * the page. So, you may begin adding components to this application * or customize the JavaScript scaffolding to fit your unique needs. */ Vue.component('image-component', require('./components/ImageuploadComponent.vue')); const app = new Vue({ el: '#app' }); I have removed the case componentfrom this file because nosotros do not need that anymore.
Stride 7: Compile the app.js file lawmaking.
We have created the component, simply the changes are not still reflected in public>> js >> app.jsfile. So need to recompile our code. Get to the CMD and hit the following command.
npm run dev
It generates an app.jsfile in public>> jsfolder. Now, include this component in the welcome.bract.phpfile.
<!doctype html> <html lang="{{ app()->getLocale() }}"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Uniform" content="IE=edge"> <meta proper name="viewport" content="width=device-width, initial-calibration=1"> <championship>File Upload Tutorial</title> <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css"> <link href="{{ asset('css/app.css') }}" rel="stylesheet"/> </head> <body> <div class="container" id="app"> <image-component></prototype-component> </div> <script> window.Laravel = <?php echo json_encode([ 'csrfToken' => csrf_token(), ]); ?> </script> <script src="{{asset('js/app.js')}}"></script> </torso> </html> Okay, now beginning the Laravel evolution server with the post-obit command.
php artisan serve
Switch to the following URL.
http://localhost:8000
See the below epitome.
Step 8: Create a grade to upload an image.
In theImageuploadComponent.vuefile, write the following lawmaking into it.
// ImageuploadComponent.vue <template> <div grade="container"> <div course="row justify-content-center"> <div grade="col-md-eight"> <div class="card card-default"> <div course="bill of fare-header">File Upload Component</div> <div form="menu-body"> <div course="row"> <div class="col-doc-ix"> <input blazon="file" v-on:alter="onImageChange" class="class-control"> </div> <div course="col-md-3"> <button class="btn btn-success btn-cake" @click="uploadImage">Upload Image</push button> </div> </div> </div> </div> </div> </div> </div> </template> <script> export default { } </script> In this component, we accept used an consequence and function, which nosotros accept not defined yet, and so let us practise that kickoff.
// ImageuploadComponent.vue <template> <div grade="container"> <div class="row justify-content-center"> <div class="col-dr.-viii"> <div class="card card-default"> <div class="card-header">File Upload Component</div> <div class="bill of fare-trunk"> <div class="row"> <div class="col-md-iii" five-if="prototype"> <img :src="image" class="img-responsive" acme="70" width="xc"> </div> <div grade="col-md-vi"> <input blazon="file" five-on:change="onImageChange" class="course-control"> </div> <div class="col-md-iii"> <button course="btn btn-success btn-block" @click="uploadImage">Upload Paradigm</button> </div> </div> </div> </div> </div> </div> </div> </template> <script> consign default { data(){ return { image: '' } }, methods: { onImageChange(e) { allow files = e.target.files || e.dataTransfer.files; if (!files.length) return; this.createImage(files[0]); }, createImage(file) { allow reader = new FileReader(); let vm = this; reader.onload = (e) => { vm.paradigm = due east.target.result; }; reader.readAsDataURL(file); }, uploadImage(){ axios.post('/image/store',{image: this.image}).then(response => { console.log(response); }); } } } </script> So, get-go, we have taken 1 belongings called an image. And so we have used the onChange event to rails the new image we take browsed. Then that image is displayed on the side div. If the image is null, and then it volition not bear witness until we browser any image. So we have used 5-if conditionals.
Note: Nosotros are sending the base 64 binary to the server. So we need to brand an prototype from that. We volition employ the Epitome intervention packet to exercise that, and so permit us first install that.
Stride 9: Install the image/intervention package.
Go to your terminal and blazon the following command to install the intervention/image package.
composer require intervention/prototype
Afterward installing the package, nosotros need to configure it into Laravel. So first, go to the config >> app.phpfile and register the Intervention Epitome Provider.
// app.php 'providers' => [ Intervention\Epitome\ImageServiceProvider::course, ]; 'aliases' => [ 'Image' => Intervention\Paradigm\Facades\Image::form, ]
Subsequently this step, we need to publish the package by the following command.
php artisan vendor:publish --provider="Intervention\Epitome\ImageServiceProviderLaravel5"
Now, we can use this package in ourImageController.phpfile.
Pace 10: Code the shop part.
Write the post-obit code into theImageController.phpfile.
// ImageController.php public office store(Asking $request) { if($request->get('prototype')) { $image = $request->get('image'); $proper noun = time().'.' . explode('/', explode(':', substr($image, 0, strpos($image, ';')))[1])[ane]; \Image::make($asking->get('epitome'))->salve(public_path('images/').$name); } $prototype= new FileUpload(); $image->image_name = $proper name; $prototype->save(); return response()->json(['success' => 'Y'all accept successfully uploaded an image'], 200); } Step eleven: Finishing our project.
Our UI looks like this.
Our terminalImageuploadComponent.vuefile looks similar this.
// ImageuploadComponent.vue <template> <div grade="container"> <div course="row justify-content-heart"> <div class="col-md-viii"> <div class="bill of fare carte-default"> <div grade="card-header">File Upload Component</div> <div class="carte-body"> <div class="row"> <div class="col-medico-iii" 5-if="epitome"> <img :src="image" grade="img-responsive" pinnacle="lxx" width="90"> </div> <div course="col-doc-6"> <input type="file" 5-on:alter="onImageChange" class="form-control"> </div> <div course="col-medico-3"> <push button class="btn btn-success btn-cake" @click="uploadImage">Upload Image</button> </div> </div> </div> </div> </div> </div> </div> </template> <script> consign default { information(){ return { image: '' } }, methods: { onImageChange(e) { let files = e.target.files || east.dataTransfer.files; if (!files.length) return; this.createImage(files[0]); }, createImage(file) { let reader = new FileReader(); allow vm = this; reader.onload = (e) => { vm.prototype = e.target.result; }; reader.readAsDataURL(file); }, uploadImage(){ axios.mail('/prototype/shop',{image: this.prototype}).then(response => { if (response.data.success) { warning(response.data.success); } }); } } } </script> And then, finally, ourVue Laravel File Upload example is over. I have already put the to a higher place lawmaking on Github. You tin check it out.
Fork Me On Github
Source: https://appdividend.com/2018/02/13/vue-js-laravel-file-upload-tutorial/
0 Response to "Single Image Upload in Vue Js Laravel"
Post a Comment