0
我想上傳到火力地堡存儲一些文件,在輸入元素更早選擇了陣營形式上傳文件Firebase.storage:從陣營形式
這是一個處理程序:通過文件對象到上傳者,並等待(我我想這樣做)從中得到回報。
// comes from input-type element, contains icon picture
handleIconFile =(e) => {
const iconFile = e.target.files[0]
// try to upload in order to get download url
const downloadURL = uploadFile(iconFile,()=>{
// takes some time ...
console.log(downloadURL);
// store url to state
this.setState({ downloadURL })
})
}
它的上傳者:它是從火力文檔拍攝,並加入return語句在成功處理程序
/** takes File Object to upload to storage
returns url for download this file from firebase */
uploadFile = (iconFile) => {
// root reference
const fileName = iconFile.name
console.log(fileName);
// const metadata = { contentType: 'image/jpeg' }
const storageRef = storage.ref()
const uploadTask = storageRef.child('/icon/'+ fileName).put(iconFile)
// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed', function(snapshot){
// Observe state change events such as progress, pause, and resume
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
var progress = (snapshot.bytesTransferred/snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
}, function(error) {
// Handle unsuccessful uploads
console.log('error:', error);
}, function() {
// Handle successful uploads on complete
var downloadURL = uploadTask.snapshot.downloadURL;
// console.log(downloadURL);
return downloadURL // <--- I did add this myself in order to return it back to handler
});
}
文件加載成功。在控制檯中我看到:Upload is 0% done
Upload is 100% done
問題是:downloadURL
不回到處理程序返回。 我可以在上傳器的成功部分看到它 - // console.log(downloadURL);
,但無法在其他任何地方看到它。
你爲什麼要傳遞第二個參數(函數)來uploadFile時只接受一個參數?你是否期待它在文件上傳後執行? – nshoes
@nshoes,我確實這麼認爲,但現在我認爲執行'uploadFile'函數的成功部分會更好,例如: '} var downloadURL = uploadTask.snapshot.downloadURL; backFire(downloadURL); }) const backFire =(url)=> { console.log(url); this.setState({downloadURL:url }) }'看起來很奇怪,但它是我發現在異步世界中返回某些東西的唯一方法。 – d2048