I am trying to achieve the task of uploading a file from my browser and sending it via POST
to an Express.js application, which will then download the file using express-fileupload.
Here is the client-side JavaScript code I have written so far:
// Triggered by onclick event of a button
function upload() {
// Retrieve the selected file (only one can be selected in the input field)
const file = document.getElementById('file').files[0];
// Check if a file is selected
if (!file) {return;}
// Add the file to a form
const form = new FormData();
form.append('file', file);
// Send the form data using fetchAPI
fetch('/upload', {
headers: {
'Content-Type': 'multipart/form-data'
},
method: 'POST',
body: form
});
}
The client-side code runs without any errors. The request appears in my network tab. The incoming request from the client is handled by this controller:
import express from 'express'
import fileUpload from 'express-fileupload'
export function uploadPOST(req: express.Request, res: express.Response) {
if (req.files) {
console.log('put')
const file: fileUpload.UploadedFile = req.files.file as fileUpload.UploadedFile
file.mv(`${settings.storage.path}/${req.app.get('username')}/${file.name}`)
}
}
In my debugging process, I noticed that req.files is always undefined, although no errors are thrown by the application.
I have also included fileUpload
and bodyParser.json()
in my middleware setup.
Others have faced similar issues and have shared their problems, but none of the solutions provided have resolved my case. I have referred to this tutorial as well: