How to upload multiple files with Vue.js and PHP
Instead of adding multiple file elements, you can use a single file element for allowing the user to upload more than one file.
Using the FormData object to pass the selected files to the PHP for upload.
In this tutorial, I show how you can upload multiple files using Vue.js and PHP.
1. Download & Include
- Download Axios package from GitHub. or you can also use CDN (https://unpkg.com/axios/dist/axios.min.js).
- Now, include
axios.min.js
withvue.js
.
<script src="vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
2. HTML
Create <div id='myapp'>
. In the <div >
create a file element and a button. Add ref
attribute in the file element which is used to access files in Vue.
Define @click='uploadFile()'
event on the button.
Display uploaded file names in <ul> <li>
.
Completed Code
<div id='myapp'>
<input type="file" id="uploadfiles" ref="uploadfiles" multiple />
<button type="button" @click='uploadFile()' >Upload file</button>
<br>
<!-- Files names -->
<div v-if="filenames.length" >
<ul >
<li v-for= '(filename,index) in filenames' >
{{ filename }}
</li>
</ul>
</div>
</div>
3. PHP
Create an ajaxfile.php
file and uploads
folder for storing the files.
Create $files_arr
to store uploaded file names.
Assign the total number of files to $countfiles
variable and assign upload location to $upload_location
variable.
Loop on the files.
Assign filename to $filename
and file extension to $ext
variable.
Initialize $valid_ext
Array with valid upload file extensions. If a file extension exists in the $valid_ext
Array then assign a new filename to $newfilename
and file path to $path
variable.
If file is successfully uploaded then initialize $files_arr
Array with $newfilename
.
Return $files_arr
Array in JSON format.
Completed Code
<?php
// To store uploaded files path
$files_arr = array();
if(isset($_FILES['files']['name'])){
// Count total files
$countfiles = count($_FILES['files']['name']);
// Upload directory
$upload_location = "uploads/";
// Loop all files
for($index = 0;$index < $countfiles;$index++){
if(isset($_FILES['files']['name'][$index]) && $_FILES['files']['name'][$index] != ''){
// File name
$filename = $_FILES['files']['name'][$index];
// Get extension
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
// Valid extensions
$valid_ext = array("png","jpeg","jpg","pdf","txt","doc","docx");
// Check extension
if(in_array($ext, $valid_ext)){
// File path
$newfilename = time()."_".$filename;
$path = $upload_location.$newfilename;
// Upload file
if(move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
$files_arr[] = $newfilename;
}
}
}
}
}
echo json_encode($files_arr);
die;
4. Script
Initialize Vue on #myapp
.
Add filename
data variable to store successfully uploaded file names.
Define uploadFile()
method which gets called on the upload button click.
Create FormData object. Loop on the selected files and append to the formData
object.
formData.append("files[]", files[index]);
NOTE – Access files using
$_FILES['files']
in PHP file.
Send AJAX request to 'ajaxfile.php'
, pass formData
object as data.
On successful callback assign response.data
to filenames
and alert number of files uploaded.
Completed Code
var app = new Vue({
el: '#myapp',
data: {
filenames: []
},
methods: {
uploadFile: function(){
var el = this;
let formData = new FormData();
// Read selected files
var files = this.$refs.uploadfiles.files;
var totalfiles = this.$refs.uploadfiles.files.length;
for (var index = 0; index < totalfiles; index++) {
formData.append("files[]", files[index]);
}
axios.post('ajaxfile.php', formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(function (response) {
el.filenames = response.data;
alert(el.filenames.length + " files is been uploaded.");
})
.catch(function (error) {
console.log(error);
});
}
}
})
5. Output
6. Conclusion
If you want to pass extra data with file instance then append the value in the FormData object.
formData.append("username", "yssyogesh");
In PHP read the passed value with the POST method.
In the example, I only added file extension validation. While implementing in your project add and update the validation according to your requirement.
0 Response to "How to upload multiple files with Vue.js and PHP"
Post a Comment