X
    Categories: PHPVue.js

VueJs Image upload and move in Laravel 5.4

VueJs Image upload and move  in Laravel 5.4

VueJs Image upload and move  in Laravel 5.4, Sometimes we need to upload user avatar without loading the form. In this case normally we will use ajax, We have built in VueJs in laravel.
Lets see how to upload and move the file using Laravel and VueJs

Step 1 : Create HTML Layout

<div class="panel-body" id="app">
    <input type="file" id="fileInput" ref = "fileInput" />
    <input type="button" name="button" >
Step 2 : Write Route
Route::post('saveImage', function(Request $request) {
} );

Step 3: Write VueJs Ajax code to upload the file

// submitform() will trigger when user press "save" button
// this.$refs.fileInput => Which will refer ref tag inside the vue element. In our case <input type="file" id="fileInput" ref = "fileInput" />
// Laravel 5.4 using "axios" to perform Http operations. In previous versions you need to use " this.http.post "

const app = new Vue({
    el: '#app',
    methods : {
    	submitform() {
    		var formData = new FormData();
    		formData.append('id', '1');
    		formData.append('image', this.$refs.fileInput.files[0]);
    		console.log(formData)
    		axios.post('http://************/saveImage', formData).then( response => {
                            console.log(response);
	    	} ).catch((error) => {
	                 console.error(error);
	            });
    	}
    }
});

Step 4 : Write laravel code to move the file inside defined Route

// Here have added very basic code. You can make it how ever you want.

Route::post('saveImage', function(Request $request) {
	$name =  Request::file('image')->getClientOriginalName();
	Request::file('image')->move(public_path('images'), $name);
	return 1;
} );

Now you can see the uploaded file inside public/images folder.

Thats it, Hope it will help someone.

 

Marimuthu: