I have been trying to do this for a while and none of these answers worked for me. This is how I did it.
I had a select file and a submit button
<input type="file" name="file" id="file">
<button onclick="javascript:doupload()" name="submit">Upload File</button>
Then in my javascript code I put this
function doupload() {
let data = document.getElementById("file").files[0];
let entry = document.getElementById("file").files[0];
console.log('doupload',entry,data)
fetch('uploads/' + encodeURIComponent(entry.name), {method:'PUT',body:data});
alert('your file has been uploaded');
location.reload();
};
What is the difference between my answer and other answers?
Other answers would use
fetch('/upload/image', {method: "POST", body: formData});
But whenever I did this I just got a 404 error because it was searching for a file to download instead of upload.
I use
fetch('uploads/' + 'filename.txt', {method:'PUT',body:data});
Instead of requesting the file, it puts the file and tells the server what data to put.
Tested with web server for chrome -
https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb?hl=en
Note- When using web server for chrome you need to go into advanced options and check the option 'enable file upload'. If you do not, you will get an error for not allowed.