存储和数据库之间的关系 - Firebase

时间:2018-01-01 00:07:04

标签: javascript reactjs firebase

我还面临另一个问题。

我正在使用firebase db来存储文本和firebase存储来存储文件。这是我的问题。

:从数据库获取特定元素时,如何从存储中获取正确的图像

这是我的尝试:

const storageRef = firebase.storage().ref('companyImages/companyImage' + 123);
                                            ^^^^^^^^^^^^ I dont have access to id yet :(
const task = storageRef.put(companyImage);

task.on('state_changed', () => {
  const percentage = (snap.bytesTransferred / snap.totalBytes) * 100; 
                               // ^^^^^^^^^^^^ not sure if i even need this
}, (err) => {
    console.log(err);
}, () => {
  firebase.database().ref('offers').push(values);
    ^^^^^^^^^^^^^^^ now I could retrieve id from it with .key but its too late
});

正如您所看到的,首先我正在做的是上传图像,当它成功时,我开始将数据上传到数据库。

尽管如此,它仍然无法正常工作。上传图片时,我必须使用正确的id对其进行命名,以便以后在组件中轻松检索。

它可能看起来有点复杂,但会欣赏任何形式的帮助。任何建议或暗示。

我应该首先将数据上传到数据库然后成像到存储?

2 个答案:

答案 0 :(得分:1)

我建议使用.getDownloadURL()。然后将所有上传的filesDownloadURL推送到对象或数组中,然后将其存储到数据库中。因此,将来你可以从你的用户/ ProfilePHotos访问这个对象或数组,然后在你的应用程序级代码中,你可以使用DownloadURL作为图像标记内的uri链接!

在此示例中,我使用的是react-native,我上传了多张照片,每次都在数组中保存下载URL,然后将数组设置为用户帐户下的firebase。

export const userVehiclePhotoUploadRequest = (photos, user, year) => dispatch => {
    console.log('Inside vehiclePhotoUpload Actions', photos, user)

    let referenceToUploadedPhotos = [];

    return new Promise((resolve, reject) => {
        photos.map(ele => {
            let mime = 'application/octet-stream'

            let uri = ele.uri
            let uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri
            let sessionId = new Date().getTime()
            let uploadBlob = null
            let imageRef = firebase.storage().ref('vehicleImages/' + `${user.account.uid}`).child(`${sessionId}`)

            fs.readFile(uploadUri, 'base64')
                .then((data) => {
                    return Blob.build(data, { type: `${mime};BASE64` })
                })
                .then((blob) => {
                    uploadBlob = blob
                    return imageRef.put(blob, { contentType: mime })
                })
                .then(() => {
                    uploadBlob.close()
                    return imageRef.getDownloadURL()
                })
                .then((url) => {
                    referenceToUploadedPhotos.push(url)
                    console.log('ARRAY OF URLS WHILE PUSHING', referenceToUploadedPhotos)
                    resolve(url)
                })
                .catch((error) => {
                    reject(error)
                })
        })
    })
        .then(() => {
            //I did this to not go home until photos are done uploading. 

            let vehicles;
            firebase.database().ref('users/' + user.account.uid + `/allVehicles/allVehiclesArray`).limitToFirst(1).once('value').then(function (snapshot) {
                // ******** This method is straight from their docs ********
                // ******** It returns whatever is found at the path xxxxx/users/user.uid ********
                vehicles = snapshot.val();
            }).then(() => {
                console.log('ARRAY OF URLS BEFORE SETTING', referenceToUploadedPhotos)
                // let lastVehicle = vehicles.length - 1;
                firebase.database().ref('users/' + user.account.uid + `/allVehicles/allVehiclesArray/` + `${Object.keys(vehicles)[0]}` + `/photosReference`).set({
                    referenceToUploadedPhotos
                }).then(() => {
                    dispatch(loginRequest(user.account))
                })
            })


        })


};

然后在您的代码中,让我们在用户信息的地图中说...

 { ele.photosReference !== undefined ? dynamicAvatar = { uri: `${ele.photosReference.referenceToUploadedPhotos[0]}` } : undefined }

答案 1 :(得分:1)

您可以在上传文件之前生成推送ID - 您也可以在task.snapshot.downloadURL保存返回快照的下载URL,这样您就不必使用存储从存储中检索文件参考文献

const offerRef = firebase.database().ref('offers').push();
const storageRef = firebase.storage().ref(`companyImages/${offerRef.key}`);
const task = storageRef.put(companyImage);

task.on('state_changed', (snap) => {
  const percentage = (snap.bytesTransferred / snap.totalBytes) * 100; 
}, (error) => {
  console.log(err);
}, () => {
  offerRef.set(values);
});