2๐
โ
use HTMLInputElement Name Properties
<input type="file" name="file" @change="changeFile" />
<input type="file" name="logo" @change="changeFile" />
<input type="file" name="headerImg" @change="changeFile" />
changeFile(e){
const name = e.target.name,
file = e.target.files[0]
const hasName = ['file', 'logo','headerImg'].includes(name)
if(hasName && file) this[name] = file
else console.log('error')
}
one of multipe image upload input
data(){
return {
// file or files
file: null,
logo: null,
headerImg: null
}
}
<input type="file" name="file" @change="changeFile" />
<input type="file" name="logo" @change="changeFile" />
<input type="file" name="headerImg" @change="changeFile" />
changeFile(e){
const name = e.target.name,
files = e.target.files,
fileLength = e.target.files.length
const hasName = ['file', 'logo','headerImg'].includes(name)
// fileLength: 1 or 2,3,4,5
if(hasName && fileLength) {
if(fileLength === 1) this[name] = files[0]
else this[name] = files // multipe: files is array,
}
else console.log('no file')
}
๐คtjp
1๐
you can try this as well-
<template>
<div class="container">
<div class="row">
<input type="file" name="file" @change="changeFile" /><br />
<input type="file" name="logo" @change="changeFile" /><br />
<input type="file" name="headerImg" multiple @change="changeFile" /><br />
</div>
</div>
</template>
<script>
export default {
data() {
return {
file: null,
logo: null,
headerImg: [],
};
},
methods: {
changeFile(event) {
try {
let files = event.target.files;
if (event.target.name === "headerImg") {
for (const property in files) {
// there are many properties in files array
// we will take only array values properties
// in which uploaded file exists. so check that property
// should be a valid number, i.e 0, 1,2
if (!isNaN(property)) {
this.headerImg.push(event.target.files[property]);
}
}
} else {
this[event.target.name] = files[0];
}
} catch (error) {
console.error(error);
}
},
},
};
</script>
๐คNeha Soni
Source:stackexchange.com