JavaScript: Upload file
Pure JS
You can use fetch optionally with await-try-catch
let photo = document.getElementById("image-file").files[0];let formData = new FormData(); formData.append("photo", photo);fetch('/upload/image', {method: "POST", body: formData});
Old school approach - xhr
let photo = document.getElementById("image-file").files[0]; // file from inputlet req = new XMLHttpRequest();let formData = new FormData();formData.append("photo", photo); req.open("POST", '/upload/image');req.send(formData);
SUMMARY
- In server side you can read original file name (and other info) which is automatically included to request by browser in
filename
formData parameter. - You do NOT need to set request header
Content-Type
tomultipart/form-data
- this will be set automatically by browser (which will include the mandatoryboundary
parameter). - Instead of
/upload/image
you can use full address likehttp://.../upload/image
(of course both addresses are arbitrary and depends on server - and same situation with parammethod
- usually on servers "POST" is used for file upload but sometimes "PUT" or other can be used). - If you want to send many files in single request use
multiple
attribute:<input multiple type=... />
, and attach all chosen files to formData in similar way (e.g.photo2=...files[2];
...formData.append("photo2", photo2);
) - You can include additional data (json) to request e.g.
let user = {name:'john', age:34}
in this way:formData.append("user", JSON.stringify(user));
- You can set timeout: for
fetch
usingAbortController
, for old approach byxhr.timeout= milisec
- This solutions should work on all major browsers.
Unless you're trying to upload the file using ajax, just submit the form to /upload/image
.
<form enctype="multipart/form-data" action="/upload/image" method="post"> <input id="image-file" type="file" /></form>
If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:
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...
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.