I am developing a file upload feature using Node.js, Vue, and Multer.
Here is the front-end code written in Vue.js
export default {
data(){
return{
selected: "How do you want to input the data?",
options: [
{ id: 1, name: 'Choose from file system' },
{ id: 2, name: 'Choose from an API' },
{ id: 3, name: 'Choose from a Database' }
],
files: []
}
},
methods: {
submitFiles(){
let formData = new FormData();
let url = axios.defaults.baseURL;
for( var i = 0; i < this.files.length; i++ ){
let file = this.files[i];
formData.append('files[' + i + ']', file);
}
axios.post( `${url}/select-files`,
formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(function(response){
console.log('SUCCESS!!');
console.log('The response object is '+response);
})
.catch(function(){
console.log('FAILURE!!');
});
},
handleFilesUpload(){
let uploadedFiles = this.$refs.files.files;
for( var i = 0; i < uploadedFiles.length; i++ ){
this.files.push( uploadedFiles[i] );
}
console.log(this.files);
}
}
}
<div id="app" class="ui equal width left aligned padded grid stackable">
<div>
<div v-if="selected === 1">
<div class="large-12 medium-12 small-12 cell">
<input type="file" id="files" ref="files" v-on:change="handleFilesUpload()"/>
<div v-if="this.files.length > 0" class="ui small basic icon buttons">
<button class="ui button" v-on:click="submitFiles()">
<i class="upload icon">
</i>Upload
</button>
</div>
</div>
<br>
</div>
</div>
</div>
Here is the code written in Node.js
// For cross origin resource sharing
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, Set-Cookie, *');
res.header('Access-Control-Allow-Credentials', 'true');
next();
})
const multer = require('multer');
let upload = multer();
app.post('/select-files', upload.single('files'), async(req, res) => {
try {
console.log(req.file);
} catch (err) {
res.sendStatus(400);
}
})
When I try testing the above code using Postman, I get the following error,

I need access to the complete file I've sent from the client. I don't know what wrong I am doing. Can someone please help me out?
The name that you appending to the formData must be the same as the file name in upload.single().
So you must replace formData.append('files[' + i + ']', file); with formData.append('files', file); for single file uploading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With