使用 JavaScript 上傳文件
要上傳輸入元素選擇的文件,您可以使用 FormData 物件。方法如下:
1.建立FormData 物件:
let formData = new FormData();
2.將檔案附加到FormData:
let photo = document.getElementById("image-file").files[0]; formData.append("photo", photo);
2.將檔案附加到FormData:
fetch('/upload/image', {method: "POST", body: formData});
3.傳送資料到伺服器:
使用fetch API,可以將FormData 傳送到指定的URL:
let progressBar = document.getElementById("progress-bar"); formData.addEventListener("progress", (event) => { if (event.lengthComputable) { let percentComplete = Math.round((event.loaded / event.total) * 100); progressBar.style.width = percentComplete + "%"; } });
監聽上傳進度
要監控上傳進度,可以使用EventTarget的addEventListener()方法:
let formData = new FormData(); let photo = document.getElementById("image-file").files[0]; formData.append("photo", photo); let progressBar = document.getElementById("progress-bar"); fetch('/upload/image', {method: "POST", body: formData}) .then((response) => { console.log(response); // Handle server response }) .catch((error) => { console.error(error); // Handle upload failure }); formData.addEventListener("progress", (event) => { if (event.lengthComputable) { let percentComplete = Math.round((event.loaded / event.total) * 100); progressBar.style.width = percentComplete + "%"; } });
以上是如何使用 JavaScript 上傳檔案並追蹤其進度?的詳細內容。更多資訊請關注PHP中文網其他相關文章!