I am currently developing a VueJS component that functions as a form to collect user information and enable multiple image uploads.
The form is set with enctype="multipart/form-data" and exhibits the following structure :
<template>
<div>
<form enctype="multipart/form-data" novalidate>
<label>Name</label>
<input type="text" v-model="name">
<label>Surname</label>
<input type="text" v-model="surname">
<label>Description</label>
<input type="text" v-model="description">
<input
type="file"
id="resources"
ref="images"
multiple
@change="handleFileUpload()"
accept="image/*">
<button @click="clear">Clear Form</button>
<button @click="submit"> Submit </button>
</div>
</form>
</template>
My handleFileUpload() function performs this action :
this.images = this.$refs.images.files
The submit function is structured in this manner :
submit () {
// Saves image to formData
let formData = new FormData()
for( var i = 0; i < this.images.length; i++ ){
let img = this.images[i];
formData.append('image[' + i + ']', img);
}
let newUser = {
name : this.name,
surname:this.surname,
description : this.description,
images : formData
}
axios.post('http://localhost:3000/api/users', newUser)
.then(() => {console.log('ok')})
.catch((err) => {console.log(err)})
}
My issue lies in the fact that the images field of newUser is being received as an empty object. I am uncertain if I should send formData in that way or if there might be an issue with the express API I've created for this purpose :
var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors());
let users = [];
app.post('/api/users',(req,res) => {
const newUser = req.body;
users.push(newUser);
res.json(users);
});
Logging newUser in the API results in this output :
{ name: 'test',
surname: 'test',
description: 'test',
images: {} }