File upload is one of the basic requirement on the web application. I am using axios package to send AJAX request to upload a file. Send a selected file using FormData object. In this tutorial, I show how you can upload a file using Vue.js and PHP.
axios.min.js
with vue.js
in the <head>
section.Create a file element and a button in the <div id='myapp'>
.
In the file element added ref='file'
which use to get the selected file in Vue script.
Add @click
event on the button which calls uploadFile()
method.
Completed Code
<div id='myapp'>
<input type="file" id="file" ref="file" />
<button type="button" @click='uploadFile()' >Upload file</button>
</div>
Create an ajaxfile.php
file and uploads
directory for storing the files.
Assign valid file extensions in $valid_extensions
Array and get the file extension from the file.
Upload the file if a file extension is found in $valid_extension
Array and return 1
otherwise 0
.
Completed Code
<?php
// File name
$filename = $_FILES['file']['name'];
// Valid file extensions
$valid_extensions = array("jpg","jpeg","png","pdf");
// File extension
$extension = pathinfo($filename, PATHINFO_EXTENSION);
// Check extension
if(in_array(strtolower($extension),$valid_extensions) ) {
// Upload file
if(move_uploaded_file($_FILES['file']['tmp_name'], "uploads/".$filename)){
echo 1;
}else{
echo 0;
}
}else{
echo 0;
}
exit;
Initialize Vue on #myapp
.
Add file
data variable and define uploadFile()
method which gets called on the upload button click.
Select the file and append in FormData
object.
Send POST request to ajaxfile.php
and pass formData
as data.
Also, set Content-Type: 'multipart/form-data'
in header.
On successful callback if response.data
is 0
then alert('File not uploaded.')
otherwise, alert('File uploaded successfully.')
.
Completed Code
var app = new Vue({
el: '#myapp',
data: {
file: "",
},
methods: {
uploadFile: function(){
this.file = this.$refs.file.files[0];
let formData = new FormData();
formData.append('file', this.file);
axios.post('ajaxfile.php', formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(function (response) {
if(!response.data){
alert('File not uploaded.');
}else{
alert('File uploaded successfully.');
}
})
.catch(function (error) {
console.log(error);
});
}
}
})
You don’t need to create a <form >
to add file element.
You can pass the extra parameter to FormData
object using append()
method which you required for processing in AJAX file.
I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others.
Originally published on makitweb.com
#vue-js #php #ajax #web-development