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
filenameformData parameter. - You do NOT need to set request header
Content-Typetomultipart/form-data- this will be set automatically by browser. - Instead of
/upload/imageyou can use full address likehttp://.../upload/image. - If you want to send many files in single request use
multipleattribute:<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)); - This solutions should work on all major browsers.
No comments:
Post a Comment