我有一个firebase功能:
//Functions and firestore requirements are here
exports.saveData = functions.https.onRequest(async (req, res) => { console.log("Data received") const busboy = new Busboy({headers: req.headers}); const fields = {} const uploads = {}
//Push fields that are not file in fields busboy.on('field', (fieldname, val) => { console.log(Processed field ${fieldname}: ${val}.
); fields[fieldname] = val; }); //Push files in uploads busboy.on('file', (fieldname, file, filename) => { console.log('File :', file); const filepath = path.join(tmpdir, filename); uploads[fieldname] = filepath; }); busboy.on('finish', () => { console.log(uploads) console.log(fields) db.collection("a_collection").add({ a: fields.a, b: fields.b, file: "Help ! From the client, I send an image. Which value do I need to save ?" }) .then(function () { res.send("Data is saved") }) .catch(function (error) { res.status(400).send(error) console.error("Error :" + error) }) });
busboy.end(req.rawBody);
}) 运行代码段展开摘要
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
在您的Firebase函数中,您正在处理HTTP请求以保存数据到Firestore数据库,并且还处理了文件上传。当客户端发送一个包含字段和文件的请求时,您的代码会分别处理这些数据。
对于非文件字段(如a
和b
),您已经正确地从请求中提取并计划将它们保存到Firestore的a_collection
集合中。但是,对于文件(特别是图片)的处理,您提到需要帮助确定如何保存它。
在您的代码中,文件被接收并存储在一个临时目录下,变量uploads[fieldname]
持有了文件的本地路径。然而,Firestore不直接支持大文件存储,如图片或视频。对于这类内容,推荐的做法是将文件上传到云存储服务(如Google Cloud Storage),然后将该文件的URL或引用信息保存在Firestore中。
为了实现这一点,您需要对代码进行一些调整:
下面是一个简化的示例流程,展示如何修改您的函数来实现这一过程:
const { Storage } = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket('your-bucket-name'); // 替换为你的bucket名称
exports.saveData = functions.https.onRequest(async (req, res) => {
// ... 其他代码保持不变 ...
busboy.on('file', async (fieldname, file, filename) => {
console.log('File :', file);
const filepath = path.join(tmpdir, filename);
uploads[fieldname] = filepath;
// 上传文件到Cloud Storage
const blob = bucket.file(filename);
const writeStream = blob.createWriteStream();
file.pipe(writeStream)
.on('finish', async () => {
await blob.makePublic(); // 如果需要公开访问权限
const fileUrl = blob.publicUrl(); // 获取公开URL
fields['fileUrl'] = fileUrl; // 保存URL到fields
});
});
busboy.on('finish', async () => {
// 确保所有文件都已上传并获得了URL
db.collection("a_collection").add({
a: fields.a,
b: fields.b,
fileUrl: fields.fileUrl // 保存图片的URL
})
.then(() => {
res.send("Data is saved");
})
.catch((error) => {
res.status(400).send(error);
console.error("Error :", error);
});
});
// ... 其他代码保持不变 ...
});
请注意,上述代码片段假设您已经设置了Google Cloud Storage的相关依赖和认证。此外,根据您的安全需求,可能还需要调整文件的访问权限设置。