How to Upload a File Using JavaScript
To upload a file using JavaScript, you can leverage the following steps:
Use Form Data:
Make an XHR Request:
Listen for Upload Events:
Example Code:
const formData = new FormData(); const fileInput = document.getElementById('image-file'); const file = fileInput.files[0]; formData.append('photo', file); const xhr = new XMLHttpRequest(); xhr.open('POST', '/upload/image'); xhr.send(formData); xhr.addEventListener('load', () => { // Handle successful upload }); xhr.addEventListener('progress', (e) => { // Monitor upload progress }); xhr.addEventListener('error', (e) => { // Handle upload errors });
Pure JavaScript:
If you want to use pure JavaScript without XHR, you can use the fetch API with FormData .
Example:
let photo = document.getElementById("image-file").files[0]; let formData = new FormData(); formData.append("photo", photo); fetch('/upload/image', { method: "POST", body: formData });
The above is the detailed content of How to Upload Files With JavaScript?. For more information, please follow other related articles on the PHP Chinese website!