【发布时间】:2019-09-01 02:31:15
【问题描述】:
我正在从上传到 Firebase 存储的每张图片中创建一个缩略图。如何获取新创建的缩略图的 downloadURL 并将其保存在 Firestore 中?
感谢您的帮助。
Firestore 中的路径:
groups --> groupId --> smallImage
我用于创建缩略图的示例代码:
const functions = require("firebase-functions");
const { Storage } = require('@google-cloud/storage');
const projectId = 'xx'
let gcs = new Storage ({
projectId
});
const spawn = require("child-process-promise").spawn;
const path = require("path");
const os = require("os");
const fs = require('fs');
// [END import]
// [START generateThumbnail]
// [START generateThumbnailTrigger]
exports.generateThumbnail = functions.storage.object().onFinalize((object) => {
// [END generateThumbnailTrigger]
// [START eventAttributes]
const fileBucket = object.bucket; // The Storage bucket that contains the file.
const filePath = object.name; // File path in the bucket.
const contentType = object.contentType; // File content type.
const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1.
const fileName = path.basename(filePath);
if (fileName.endsWith('_small')) {
console.log('Already a Thumbnail.');
return null;
}
// [START thumbnailGeneration]
// Download file from bucket.
const bucket = gcs.bucket(fileBucket);
const tempFilePath = path.join(os.tmpdir(), fileName);
const metadata = {
contentType: contentType,
};
return bucket.file(filePath).download({
destination: tempFilePath,
}).then(() => {
console.log('Image downloaded locally to', tempFilePath);
// Generate a thumbnail using ImageMagick.
return spawn('convert', [tempFilePath, '-thumbnail', '200x200>', tempFilePath]);
}).then(() => {
console.log('Thumbnail created at', tempFilePath);
const thumbFileName = path.basename(filePath) + '_small';
const thumbFilePath = path.join(path.dirname(filePath), thumbFileName);
// Uploading the thumbnail.
return bucket.upload(tempFilePath, {
destination: thumbFilePath,
metadata: metadata,
});
// Once the thumbnail has been uploaded delete the local file to free up disk space.
}).then(() => fs.unlinkSync(tempFilePath));
// [END thumbnailGeneration]
});
【问题讨论】:
标签: node.js firebase google-cloud-firestore google-cloud-functions firebase-storage