【发布时间】:2020-07-04 03:09:20
【问题描述】:
我正在尝试使用云函数验证我的 Firebase 存储中帖子的图像尺寸。我想做的是:
1:让用户上传图片
2:上传后,后端检查尺寸
2.1:如果它具有良好的尺寸,请不要删除它
2.2:否则,将其从存储中删除
代码如下:
// Validate image dimensions
exports.validateImageDimensions = functions
.region("us-central1")
.runWith({ memory: "1GB", timeoutSeconds: 120 })
.storage.object()
.onFinalize(async (object) => {
// Get the bucket which contains the image
const bucket = gcs.bucket(object.bucket);
// Get the name
const filePath = object.name;
// Check if the file is an image
const isImage = object.contentType.startsWith("image/");
// Check if the image has valid dimensions
const hasValidDimensions = true; // TODO: How to get the image dimension?
// Do nothing if is an image and has valid dimensions
if (isImage && hasValidDimensions) {
return;
}
try {
await bucket.file(filePath).delete();
console.log(
`The image ${filePath} has been deleted because it has invalid dimensions.`
);
// TODO - Remove image's document in firestore
} catch (err) {
console.log(`Error deleting invalid file ${filePath}: ${err}`);
}
});
但我不知道如何获取对象尺寸。我检查了文档但没有答案。
有什么想法吗?
【问题讨论】:
-
我认为我必须为维度创建自定义元数据,但要寻找更容易的东西
-
您将不得不查找并使用图像处理库来查找有关图像的信息,例如Sharp 或imagemagick。
-
@VictorMolina 我很好奇,你最后做了什么?我也面临这个问题
标签: node.js firebase google-cloud-functions google-cloud-storage