文章大綱
呼叫api上傳圖片時候如果要顯示進度條,目前有兩種方式可以加入偵聽事件,
- 使用
js原生的XMLHttpRequest - 使用axios
其實axios也只是把偵聽事件的名稱改掉而已,背後做法應該是一樣的XD
1. js原生XMLHttpRequest
先把進度條與input的html架構完成。
<input type="file" />
<progress value={0} max="100" />
當我們點擊input選好檔案之後,執行handeChangeFile
const [progress, setProgress] = useState(0);
const handleChangeFile = (e) => {
const file = e.target.files[0];
const formData = new FormData();
formData.append("file", file);
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", function (e) {
const percentComplete = (e.loaded / e.total) * 100;
setProgress(percentComplete);
});
xhr.addEventListener("load", function (e) {
// 上傳完成後要做的事,可以在這邊顯示圖片
});
xhr.open("POST", "http://localhost:5001/api/upload");
xhr.send(formData);
};
我們新增了一個事件progress,它會持續傳送目前進度,經過一些計算轉換成百分比之後,把百分比數字綁定到進度條上面。
<input type="file" onChange={handleChangeFile} />
<progress value={progress} max="100" />
2. 使用axios
axios有幫我們整合出一個參數onUploadProgress,並且返回的內容就跟上面原生的progress 事件一樣。
const handleChangeFile = (e) => {
const file = e.target.files[0];
var formData = new FormData();
formData.append("file", file);
axios
.post("http://localhost:5001/api/upload", formData, {
onUploadProgress: function (e) {
const percentComplete = (e.loaded / e.total) * 100;
setProgress(percentComplete);
},
})
.then(function (response) {
// 上傳完成後要做的事,可以在這邊顯示圖片
})
.catch(function (error) {
console.log(error);
});
};
http://localhost:5001/api/upload 是後端接收檔案的api網址,通常會回應圖片上傳後的結果與路徑。





發表評論
想要加入討論嗎?請盡情發表您的想法!