我正在从上传到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]
});
是的,你的bucket.upload()函数可以返回你需要的File对象:
const options = {destination: thumbFilePath, metadata: metadata};
bucket.upload(tempFilePath, options, function(err, file, apiResp) {
// `file` is an instance of a File object that refers to your new file.
const request = require('request');
const config = {
action: 'read',
expires: '03-17-2025'
};
file.getSignedUrl(config, function(err, url) {
if (err) {
console.error(err);
return;
}
// The file is now available to read from this URL.
request(url, function(err, resp) {
// resp.statusCode = 200
});
});
});
见:https://cloud.google.com/nodejs/docs/reference/storage/2.3.x/File#getSignedUrl