[英]After Completing progress in bar, URL is not being generated even though File is Uploaded
After file is uploaded and progress bar completes till 100 , URL isn't generated but if I remove code of progress, URL is generated文件上传和进度条完成直到 100 后,不会生成 URL 但如果我删除进度代码,则会生成 URL
const handleChange = async (e) => {
const file = e.target.files[0];
//Path of the file.
const storageRef = storage.ref("files/");
const fileRef = storageRef.child(file.name);
//Upload files in firebase storage.
const time= await fileRef.put(file).on(
"state_changed",
(snapshot) => {
const progress = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);
setprogress(progress);
}
)
//URL being generated
setUrl(await fileRef.getDownloadURL());
storage.refFromURL(url);
};
I overridden the functions of the on
callback, and I'm generating the URL in the complete
event, this behaviour is explained in more detail in this Firebase storage document我覆盖了
on
回调函数,并在complete
事件中生成 URL,此Firebase 存储文档中更详细地解释了此行为
var storage = firebase.storage().ref("files/").child(file.name);
//upload file
var upload = storage.put(file);
//update progress bar
upload.on(
"state_changed",
function progress(snapshot) {
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
setprogress(percentage);
},
function error() {
alert("error uploading file");
},
function complete() {
// generate URL
storage
.getDownloadURL()
.then(function(url) {
console.log(url);
})
.catch(function(error) {
console.log("error encountered");
});
});
As we had callback for setState in the class component for React, you have to do something like that由于我们在 React 的类组件中对 setState 进行了回调,因此您必须执行类似的操作
setUrl(await fileRef.getDownloadURL());
useEffect to watch that state change useEffect 观察状态变化
useEffect(() => {
storage.refFromURL(YOUR_URL_STATE);
}, [YOUR_URL_STATE]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.