我是节点js和谷歌云功能的新手。我能够调整图像大小以生成缩略图。我无法弄清楚的是如何获取新生成的缩略图的下载URL。这是代码
exports.generateThumbnail = functions.storage.object('{pushId}/ProductImages').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 resourceState = object.resourceState; // The resourceState is 'exists' or 'not_exists' (for file/folder deletions).
const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1.
console.log("this is the object ",object);
// [END eventAttributes]
// [START stopConditions]
if (!contentType.startsWith('image/')) {
console.log('This is not an image.');
return null;
}
const fileName = path.basename(filePath);
if (fileName.startsWith('thumb_')) {
return null;
}
// [END stopConditions]
// [START thumbnailGeneration]
// Download file from bucket.
const bucket = gcs.bucket(fileBucket);
const tempFilePath = path.join(os.tmpdir(), fileName);
// const tempFilePath1 = path.join(os.tmpdir(), fileName+"1");
// var storageRef = firebase.storage.ref("folderName/file.jpg");
const storageRef = event.data.ref.parent;
// return storageRef.getDownloadURL().then(function(url) {
// });
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(() => {
const thumbFileName = `thumb_${fileName}`;
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));
});
在javascript中,可以使用此代码
获取上传到firebase存储的图像的downloadurl storageRef.put(file, metadata).then(function(snapshot) {
var url = snapshot.downloadURL;
})
如何在节点js中获取已调整大小的图像的下载URL?
答案 0 :(得分:3)
您需要使用getSignedUrl()生成公开网址。 generate-thumbnail example中的functions-samples repo中有一个示例。缩写:
const thumbFile = bucket.file(thumbFilePath);
const config = {
action: 'read',
expires: '03-01-2500',
};
thumbFile.getSignedUrl(config); // returns a promise with results
您必须注意README并使用服务帐户初始化admin SDK才能使用此方法。云功能的默认初始化将无效。