問題描述
如何等到使用 Axios 上傳文件 (How to wait until file is uploaded using Axios)
我正在開發一個 Reactjs 項目,我可以在其中上傳和下載文件。
但是當我上傳文件時,來自 Axios 的請求 PUT 在文件完全上傳到我的數據庫之前完成。我使用Axios的onUploadProgress,點擊上傳按鈕後直接顯示100%,而文件尚未上傳。
似乎背面文件的上傳只是開始一旦進度條達到 100%。不知道如何正確同步進度條和文件上傳。
我的代碼
前面
p> onUpload() {
const data = new FormData();
for (var i = 0; i < this.state.selectedFile.length; i++) {
data.append("file", this.state.selectedFile[i]);
}
axios
.put("http://localhost:5000/api/files/upload", data, {
onUploadProgress: ProgressEvent => {
this.setState({
loaded: Math.round(
(ProgressEvent.loaded * 100) / ProgressEvent.total
)
});
}
})
.then(res => {
console.log("File(s) uploaded", res);
});
}
返回
export const uploadFile = (req, res) => {
const myFile = (Array.isArray(req.files.file)
? req.files.file
: [req.files.file]
).filter(e => e);
// upload file(s) to directory
for (let i = 0; i < myFile.length; i++) {
myFile[i].mv("./src/uploads/" + myFile[i].name, function(err) {
if (err) {
return res.status(500).send(err);
}
});
// save file(s) to database
Upload.create({
type: myFile[i].mimetype,
name: myFile[i].name,
data: myFile[i].data
});
}
res.send("file uploaded !");
};
方法 2:
You are setting state as soon as you're hitting the API, the reason you're getting 100% as soon as the API hits. I would suggest you to pass "status = success"
or "status = 201"
from server side So that you can wait for a response in client side. i.e :‑
onUpload() {
const data = new FormData();
for (var i = 0; i < this.state.selectedFile.length; i++) {
data.append("file", this.state.selectedFile[i]);
}
axios
.post("http://localhost:5000/api/files/upload", data, {
headers: {
"Content‑type": "multipart/form‑data"
}
})
.then(res => {
if(res.status === 'success') {
onUploadProgress: ProgressEvent => {
this.setState({
loaded: Math.round(
(ProgressEvent.loaded * 100) / ProgressEvent.total
)
});
}
}
console.log("File(s) uploaded", res);
});
}
(by akromx、Sachin Vishwakarma、Sohan)