当存储桶中的文件被覆盖时,下载URL更改。如何保留原始网址

时间:2019-04-15 14:58:17

标签: node.js google-cloud-functions firebase-storage

我已经成功地为云存储创建了一个触发器,该触发器可以调整大小并覆盖原始图像文件。

return destBucket.file(filePath).download({
    destination: tempFilePath
}).then(() => {
    return spawn('convert', [tempFilePath, '-resize', '150x150', tempFilePath])
}).then(() => {
    metadata.isResized = true
    return destBucket.upload(tempFilePath,
        {
            destination: path.join(path.dirname(filePath), path.basename(filePath)),
            metadata: { metadata: metadata }
        })
}).then(() => fs.unlinkSync(tempFilePath))
});

但是,这也会更改我存储在Firestore数据库中的文件的下载URL

const pathRef = storageRef.ref('profileImg/' + uid + '/' + image.name)
        pathRef.put(image).then(() => {
            //Get logo URL
            const starsRef = storageRef.ref().child('profileImg/' + uid + '/' + image.name)
            starsRef.getDownloadURL().then((url) => {
                changeProfile({ profile: profile, profileImg: url }).then((result) => {
                    dispatch(progressSuccess(result))
                }).catch((error) => {
                    dispatch(progressFailed(error.message))
                });
            }).catch((error) => {
                dispatch(progressFailed(error.message))
            })

有什么办法可以将原始下载URL保留在覆盖的文件中?还是有什么方法可以完成这项任务?

1 个答案:

答案 0 :(得分:0)

好吧,我不得不采取另一种方法来执行此任务,因为我认为没有办法保留原始URL。现在基本上,我在一个存储触发功能中完成了所有操作(调整图像大小,删除原始图像,获取url,更新用户数据库)。

return destBucket.file(filePath).download({
    destination: tempFilePath
})
    .then(() => {
        console.log('The file has been downloaded to', tempFilePath)
        return spawn('convert', [tempFilePath, '-resize', '140x140', tempLocalJPEGFile])
    }).then(() => {
        console.log('JPEG image created at', tempLocalJPEGFile)
        metadata.modified = true
        return destBucket.upload(tempLocalJPEGFile,
            {
                destination: JPEGFilePath,
                metadata: { metadata: metadata }
            })
    }).then(() => {
        console.log('JPEG image uploaded to Storage at', JPEGFilePath)
        return destBucket.file(filePath).delete()
    }).then(() => {
        console.log('Original file deleted', filePath)
        const logo = storageRef.file(JPEGFilePath)
        return logo.getSignedUrl({ action: 'read', expires: '03-09-2491' })
    }).then((url) => {
        const newRef = db.collection("user").doc(uid)
        return newRef.set({
            profile: {profileImg: url[0]}
        }, {
            merge: true
        })
    }).then(()=> {
        fs.unlinkSync(tempFilePath);
        fs.unlinkSync(tempLocalJPEGFile)
        console.log('User database updated')
        return null
    })
})

我不确定这是否是最佳做法,因此请随时发表评论或更新。我还不知道是否有更好的方法从存储图像的存储桶中获取文件夹名称,该名称被命名为更新数据库所需的用户ID值(userImg / [userIdHere] /image.jpg)。老式的拆分代码

const uid = filePath.split("/").slice(1,2).join("")

但是此触发器将使存储桶仅可用于用户图像,因为我们不能对存储桶中的某些文件夹使用触发器