问题描述
背景:我正在使用 Firebase Cloud Functions、新的 Firestore 数据库和带有 Android 客户端的存储桶.
Background: I'm using Firebase Cloud Functions, the new Firestore Database, and storage bucket with an Android client.
我想要完成的事情:当用户将图片上传到存储桶时,我想使用云功能获取存储桶中图像位置的文件路径/链接,并将此字符串作为新文档存储在名为图片"的新集合下当前登录用户在 Firestore 中的文档.
What I want to accomplish:When a user uploads a picture to a storage bucket, I want to use cloud functions to get the file path/link to the image location in the storage bucket and store this string as a new document under a new collection called "pictures" under the currently logged in user's document in Firestore.
这样,我可以在 Firestore 中看到每个用户直接上传的图像,并且可以更轻松地将特定用户的图像拉到 Android 客户端.
That way, I can see the images each user has uploaded directly in Firestore and it makes it easier to pull a specific user's images down to the Android client.
到目前为止我已完成的工作:1. 用户首次登录时,会在新的 Firestore 数据库中创建一个用户文档.2. 登录用户可以上传图片到存储桶.3.使用Firebase Cloud Functions,我设法获得了存储位置的文件路径/链接如下:
What I've completed so far: 1. When a user logs in for the first time, it creates a user doc in the new Firestore Database. 2. A logged in user can upload an image to a storage bucket. 3. Using Firebase Cloud Functions, I managed to get the file path/link of the storage location as follows:
/**
* When a user selects a profile picture on their device during onboarding,
* the image is sent to Firebase Storage from a function running on their device.
* The cloud function below returns the file path of the newly uploaded image.
*/
exports.getImageStorageLocationWhenUploaded = functions.storage.object().onFinalize((object) => {
const filePath = object.name; // File path in the bucket.
const contentType = object.contentType; // File content type.
// Exit if this is triggered on a file that is not an image.
if (!contentType.startsWith('image/')) {
console.log('This is not an image.');
return null;
}
console.log(filePath);
});
问题:如何使用 Cloud Functions 获取当前登录用户并将该用户上传的图像文件路径/链接作为新文档存储在 Firestore 数据库中的该登录用户文档下?
Question: How do I get the currently logged in user and store this user's uploaded image file path/link as a new doc under this logged in user's documents within the Firestore database using Cloud Functions?
推荐答案
目前,使用 Cloud Storage 触发器,您无权访问经过身份验证的用户信息.要解决这个问题,您必须执行一些操作,例如将 uid 嵌入文件的路径中,或将 uid 作为元数据添加到文件上传中.
Currently, with Cloud Storage triggers, you don't have access to authenticated user information. To work around that, you'll have to do something like embed the uid in the path of the file, or add the uid as metadata in the file upload.
这篇关于如何在 Cloud Functions 存储触发器中获取经过身份验证的 Firebase 用户的 uid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!