I successfully managed to store files on my computer by utilizing the HTML form action attribute and then processing this request on my Express webserver.
However, when I attempted to switch to using an event listener on the submit button of the form instead of relying on the action attribute to send the post request, I encountered difficulties in making it work.
Specifically, I encountered a 400 bad request error message.
Fetch
let form = document.querySelector('#uploadForm')
let inpFile = document.querySelector('#inpFile')
form.addEventListener('submit', async event => {
event.preventDefault()
const formData = new FormData()
formData.append('inpFile', inpFile.files[0])
fetch('http://myip/upload', {
method: 'POST',
headers: {
'Content-Type' : 'multipart/form-data'
},
body: formData
}).catch(console.error)
})
HTML
<form ref='uploadForm'
id='uploadForm'
method='post'
encType="multipart/form-data">
<input type="file" name="sampleFile" id="inpFile" />
<input type='submit' value='Submit' />
</form>
Express Server
const express = require('express')
const app = express();
const path = require('path')
const things = require('./routes/things')
const fileUpload = require('express-fileupload')
app.post('/upload', (req, res) => {
let sampleFile = req.files.sampleFile
sampleFile.mv(__dirname + '\\files\\' + sampleFile.name, (err) => {
if (err)
return res.status(500).send(err)
res.send('File uploaded!')
})
})