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 });
以上是如何使用 JavaScript 上傳檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!