I can grab the file input and handle the form submission. But I’m stuck on how to actually send the file with fetch. My attempt looks like this:
document.querySelector('form').addEventListener('submit', function(e) {
e.preventDefault();
const file = document.getElementById('fileInput').files[0];
fetch('/upload', {
method: 'POST',
// What should I put here for the body and headers?
})
.then(response => console.log('File uploaded'))
.catch(error => console.error('Upload failed', error));
});
Can someone explain what I need to add to make this work? I’m not sure about the body and headers for sending files.
This approach automatically sets the correct Content-Type header. Make sure your server is set up to handle multipart/form-data requests for file uploads.
This approach worked like a charm for me. Just make sure your server can handle multipart/form-data. Also, don’t set the Content-Type header manually - the browser handles that automatically with FormData. Good luck with your upload feature!