【发布时间】:2023-04-08 00:10:01
【问题描述】:
我正在测试一个 Vue 应用程序,用户应该能够将图像上传到 Firebase,并且一旦上传了该图像,它应该保存到 img 标签内的模板中。
我上传图片没有问题,但我不知道如何检索它们并让它们出现在应用程序中。
我尝试复制粘贴我在 Stack 上找到的方法,但它不适合我。
我也试过搜索各种教程,但都只关注上传部分。
谁能帮帮我?
更新:
我设法通过将v-for 从file 更改为imgURL 来预览要显示的上传图像,但我仍然遇到问题。
图像仍未保存到模板中。当我按下上传按钮时,图像在页面上显示为预览 130 次,但当我刷新页面时消失。
<template>
<div>
<h2>image upload</h2>
<input type="file" @change="uploadImage" value="upload" id="fileButton" ref="myFiles">
<div class="image_section_content" fluid v-for="files in file" :key="files.id">
<b-img :src="this.imgURL" fluid alt="Responsive image"></b-img>
<progress max="100" :value="value" id="uploader">0%</progress>
</div>
</div>
</template>
<script>
import db from '@/firebase/init'
import firebase from 'firebase'
export default {
name: 'ImageUpload',
data () {
return {
value: 0,
fileButton: document.querySelector("#fileButton"),
file: [],
imgRef: null,
imgURL: null
}
},
methods: {
uploadImage(e){
//get file
this.file = this.$refs.myFiles.files[0]
console.log(this.file)
//create storageref
let storageRef = firebase.storage().ref('images/');
//save image reference
this.imgRef = storageRef.fullPath;
//upload file
let task = storageRef.put(this.file);
task.on('state_changed', (snapshot) => {
let percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
this.value = percentage;
snapshot.ref.getDownloadURL().then(
(DownloadURL) => {
this.imgURL = DownloadURL;
console.log(this.imgURL)
}
)
})
},
// Output image
mounted() {
const id = this.$route.params.id;
const storageRef = firebase.storage().ref('images/');
storageRef.get().then(doc => {
if (doc.exists) {
console.log(doc.data())
this.imgURL = doc.data().imgURL
} else {
console.log('no data')
}
}).catch(err => {
console.log(err)
})
}
}
}
【问题讨论】:
-
你有没有调试过你的方法来获取图像并查看那里发生了什么?
-
你在
imgURL变量中得到正确的图片URL吗? -
我尝试查看控制台。该图像已成功上传到我的 Firebase 存储中的图像文件夹,但我没有在应用程序中获得任何输出。我在控制台中没有收到任何错误。
-
<b-img :src="imgURL" fluid alt="Responsive image"></b-img>不需要在src中添加this
标签: javascript firebase vue.js firebase-storage