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 input let 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.