Suppose you have an HTML element representing a button that lets users select a file. Upon clicking the button and choosing a file, its name is stored in document.getElementById("image-file").value. If the server supports multi-part POST requests at the URL "/upload/image," how do you send the file to that endpoint? Additionally, how do you monitor the upload's progress?
You can use the fetch API with optional await-try-catch handling:
let photo = document.getElementById("image-file").files[0]; let formData = new FormData(); formData.append("photo", photo); fetch('/upload/image', {method: "POST", body: formData});
This example also includes user data sent as JSON:
async function SavePhoto(inp) { let user = { name: 'john', age: 34 }; let formData = new FormData(); let photo = inp.files[0]; formData.append("photo", photo); formData.append("user", JSON.stringify(user)); const ctrl = new AbortController(); // for timeout setTimeout(() => ctrl.abort(), 5000); try { let r = await fetch('/upload/image', { method: "POST", body: formData, signal: ctrl.signal, }); console.log('HTTP response code:', r.status); } catch (e) { console.log('Huston we have problem...:', e); } }
Unfortunately, methods like request.onprogress are not supported in HTML5 file upload with fetch, but you can monitor the overall upload progress by listening to network events:
let xhr = new XMLHttpRequest(); xhr.upload.addEventListener('progress', function(e) { if (e.lengthComputable) { let percentComplete = (e.loaded / e.total) * 100; console.log('Upload progress:', percentComplete '%'); } }); xhr.open('POST', '/upload/image'); xhr.send(formData);
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3