Hey guys i am trying to make an app in which i neeed to upload multiple files but in my node backend when i try to upload files using postman it works but while using with vue js it does not work
this is my node backend where i use formidable and try to upload images
app.post('/multiple', (req, res) => {
var form = new formidable.IncomingForm(),
files = [],
fields = [];
form.on('field', function (field, value) {
console.log('fields is', field);
fields.push([field, value]);
});
form.on('file', function (field, file) {
console.log('i came inside file');
console.log(file.name);
const oldPath = file.path;
const newPath = path.join(__dirname, 'uploads/' + file.name);
const rawData = fs.readFileSync(oldPath);
console.log('old path', oldPath);
fs.writeFileSync(newPath, rawData);
console.log('file uploaded');
console.log(JSON.stringify(field));
files.push([field, file]);
});
form.on('end', function () {
console.log('done');
});
form.parse(req);
console.log(files);
return res.json(files);
});
and this is my vue js front end component code
this is html code for vue js
<template>
<div>
<button @click="items++">Add One More File</button>
<form @submit.prevent="handleImageUpload">
<div v-for="item in items" :key="item">
<input type="file" @change="handleFile($event, item)" />
</div>
<input type="submit" />
</form>
</div>
</template>
and this is script tag for component
<script>
import axios from 'axios';
export default {
data() {
return {
items: 1,
files: [],
};
},
methods: {
async handleImageUpload() {
try {
const fd = new FormData();
this.files.map((index, file) => {
fd.append(index, file);
});
const { data } = await axios.post('http://localhost:5000/multiple', fd);
console.log('data from backend is ', data);
} catch (error) {
console.log(error);
}
},
handleFile(e, item) {
console.log(e);
this.files[item - 1] = e.target.files[0];
},
},
};
</script>
now what happend when I request backend with form data everything goes undefined there
ok so it was my mistake, I was writing map function the wrong way it should be
this.files.map((file,index) => {
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.