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="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();
};
If you like StackSnippets...
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');
};
<input type="file" name="file" id="file">
<button onclick="doupload()" name="submit">Upload File</button>
The PUT
method is slightly different than the POST
method. In this case, in web server for chrome, the POST
method is not implemented.
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.