[英]adding files to firebase storage in vue.js from forms
我正在尝试使用vue.js将图像添加到Firebase存储中
我的代码编译了如何将我没有获得任何结果的数据添加到Firestore中,我想获得下载URL以及任何建议
methods: {
saveNewAticle() {
db
.collection("storys")
.add({
title: this.title,
summary: this.summary,
article: this.article
})
.then(docRef => {
console.log("Client added: ", docRef.id);
this.$router.push("/");
})
.catch(error => {
console.error("Error adding employee: ", error);
});
//links ref
//https://firebase.google.com/docs/storage/web/start
var storageref= storage.ref()
var thumbnailref = storageref.child ("images")
var file = thumbnail
var uploadTask = storageRef.child('images/${file}').put(file)
uploadTask
.on(firebase.storage.TaskEvent.STATE_CHANGED,
function(snapshot) {
// /Upload completed successfully, now we can get the download URL
uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
});
})
}
}
在函数uploadTask.on(eventName, firstObserver, secondObserver, thirdObserver)
每次状态更改时都会调用firstObserver
secondObserver
是错误观察器,在失败时被调用
上传完成thirdObserver
调用thirdObserver
要获取下载网址,您需要签入第3个观察者
uploadTask
.on(firebase.storage.TaskEvent.STATE_CHANGED,
function() {},
function() {},
function(snapshot) {
// /Upload completed successfully, now we can get the download URL
uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
});
})
除了ittus的答案外,请注意,在saveNewAticle()
方法中,您正在调用两个异步操作( add()
和put()
),而没有链接它们。
由于您在完成数据库写操作后(即,当add()
方法返回的promise解析后)离开了当前网页(使用this.$router.push("/");
),因此您可以离开该页面在完成Firebase Storage的put()
方法之前 。
为了避免这种行为,您应该将这两种方法返回的承诺链接在一起。 由于只对知道何时完成上传感兴趣,因此可以按以下方式使用then()
方法(而不是使用on()
监听事件):
saveNewAticle() {
db
.collection("storys")
.add({
title: this.title,
summary: this.summary,
article: this.article
})
.then(docRef => {
console.log("Client added: ", docRef.id);
var storageref = storage.ref()
var thumbnailref = storageref.child("images")
var file = thumbnail
var uploadTask = storageRef.child('images/${file}').put(file)
return uploadTask;
})
.then(uploadTaskSnapshot => {
return uploadTaskSnapshot.ref.getDownloadURL();
})
.then(downloadURL => {
console.log('File available at', downloadURL);
this.$router.push("/");
})
.catch(error => {
console.error("Error adding employee: ", error);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.