如何在Firebase存储上传文件,然后将url存储在带有vue 3的firestore中(组成API)



我是firebase和vue 3的新手,我有上传到存储的问题,我正在firebase上上传文件(图像),并希望将其与输入的所有其他数据一起存储到firestore,我可以从表单中保存所有数据,但无法使用文件url,我使用以下功能:

<input @change="uploadTaskPromise" class="file-input" type="file" name="file">
import { getStorage, ref as stRef, uploadBytesResumable, getDownloadURL } from "firebase/storage";

const uploadTaskPromise = (e) => {
const file = e.target.files[0];
const storage = getStorage();
const metadata = {
contentType: 'image/jpeg'
};

const storageRef = stRef(storage, 'products/' + file.name);
const uploadTask = uploadBytesResumable(storageRef, file, metadata);

uploadTask.on('state_changed',
(snapshot) => {

const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case 'paused':
console.log('Upload is paused');
break;
case 'running':
console.log('Upload is running');
break;
}
}, 
(error) => {

switch (error.code) {
case 'storage/unauthorized':

break;
case 'storage/canceled':

break;
// ...
case 'storage/unknown':

break;
}
}, 
() => {

getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {

console.log('File available at', downloadURL);
resolve({ imgUrl: downloadURL });
});
});
}

首先,我制作了一个简单的表单。。。

<template>
<form action="#" @submit.prevent>
<div>
<label for="title">Product title</label>
<input v-model="title" type="text" id="title" placeholder="Title" />
</div>
<div>
<label for="price">Product price</label>
<input v-model="price" type="number" id="price" min="0" placeholder="0.00" />
</div>
<div>
<label for="file">Product photo</label>
<input @change="handleFileChange" type="file" id="file" />
</div>
<button @click="submitForm">Send</button>
</form>
</template>

并将其与脚本连接

<script>
// this variables setup-ed in config.js
import { storage, productsCollectionRef } from '../firebase/config'
// this function from firebase. need to upload file
import { ref, uploadBytesResumable, getDownloadURL } from 'firebase/storage'
// this one for creating document in database (firestore) 
import { addDoc } from 'firebase/firestore'
export default {
// child component, imported in main App.vue
name: 'vue-upload',
data() {
return {
title: null,
price: 0,
file: null
}
},
methods: {
handleFileChange(e) {
// when file selected - update property in data()
this.file = e.target.files[0]
},
createProduct(data) {
// pass a reference to collection and data
addDoc(productsCollectionRef, data)
},
uploadFile(file) {
// getting name & type properties from File object
const { name, type } = file
// create a reference to file in firebase
const storageRef = ref(storage, 'images/' + name)
// upload file (this.file) to firebase and append metadata
const uploadTask = uploadBytesResumable(storageRef, this.file, {
contentType: type
})
uploadTask.on(
'state_changed',
(snapshot) => {
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
console.log('Upload is ' + progress + '% done')
},
(error) => {
console.log(error)
},
() => {
// successful upload. get url ...
getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
// ... make a data to write ...
const data = {
title: this.title,
price: this.price,
url: downloadURL
}
// ... and call a fn that writes a document to a firestore
this.createProduct(data)
})
}
)
},
submitForm() {
// just quick & simple validation
if (this.title && this.price && this.file) {
this.uploadFile(this.file)
return
}
alert('Form invalid')
}
}
}
</script>

您可能会注意到import { storage, productsCollectionRef } from '../firebase/config'行。这只是另一个js文件,我在其中传递firebase:的配置

/firebase/config.js

import { initializeApp } from 'firebase/app'
import { getStorage } from 'firebase/storage'
import { getFirestore, collection } from 'firebase/firestore'
const firebaseConfig = {
apiKey: 'XXXXX',
authDomain: 'XXXXX',
projectId: 'XXXXX',
storageBucket: 'XXXXX',
messagingSenderId: 'XXXXX',
appId: 'XXXXX'
}
// Initialize Firebase
const app = initializeApp(firebaseConfig)
const storage = getStorage(app)
const db = getFirestore(app)
// i've made a 'products' collection in my firestore database [screenshot][1]
const productsCollectionRef = collection(db, 'products')
// we need export this setuped variables for use in another file
export { storage, productsCollectionRef }

@bahyllam我没有足够的声誉来添加评论。

在上一段代码中(4月10日5:05),this.files中有一个数组,但uploadFile(file)函数使用单个file作为参数。因此,在这个函数中,您需要对整个数组进行循环,并分别调用每个file的所有代码(为每个文件获取一个name&type,生成storageRefuploadTask。但只进行一次写入操作:

handleFileChange(e) {
if (e.target.files) {
for (const file of e.target.files) {
this.files.push(file)
}
}
}
uploadFile() {
const urls = []
const promises = []
this.files.forEach((file) => {
// getting name & type properties from each File object
const { name, type } = file
// create a reference to each file in firebase
const storageRef = ref(storage, 'images/' + name)
// upload each file to firebase and append metadata
const uploadTask = uploadBytesResumable(storageRef, file, {
contentType: type
})
// create task with promises. this will help us to expect the result correctly
const promise = new Promise((resolve, reject) => {
uploadTask.on(
'state_changed',
(snapshot) => {
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
console.log('Upload is ' + progress + '% done')
},
(error) => {
console.log(error)
reject(error)
},
async () => {
// wait for URL from getDownloadURL 
const url = await getDownloadURL(uploadTask.snapshot.ref)
urls.push(url)
resolve(url)
}
)
})
// add task to "waitlist"
promises.push(promise)
})
// when all "waitlist" resolve ...
Promise.all(promises).then(() => {
// ... make a data to write ...
const data = {
title: this.title,
price: this.price,
// url: [Array]
url: urls
}
// ... and call a fn that writes a document to a firestore
this.createProduct(data)
})
}

相关内容

  • 没有找到相关文章

最新更新