【发布时间】:2019-01-18 00:24:45
【问题描述】:
我正在尝试根据上传的文件创建缩略图,但我不确定这是否是实现此目的的正确方法。现在下面的代码不断创建缩略图。 if (fileName.startsWith(THUMB_PREFIX)) {这部分是问题所在。
是否有基于此示例创建多个缩略图的更简单方法? https://github.com/firebase/functions-samples/blob/master/generate-thumbnail/functions/index.js
exports.onFileChange = functions.storage.object()
.onFinalize((object) => {
const sizes = [200, 50];
const timestamp = + new Date();
sizes.forEach((size, index) => {
// File and directory paths.
const filePath = object.name;
const contentType = object.contentType; // This is the image MIME type
const fileDir = path.dirname(filePath);
let fileName = path.basename(filePath);
let newFileName = path.basename(filePath)
let currentThumbURL = '';
const filename = fileName.substr(0, fileName.indexOf('.'));
let fileExtension = fileName.split('.').pop();
fileName = filename + timestamp + '.' + fileExtension;
const thumbFilePath = path.normalize(path.join(fileDir, `${THUMB_PREFIX}-${size}-${fileName}`));
const tempLocalFile = path.join(os.tmpdir(), filePath);
const tempLocalDir = path.dirname(tempLocalFile);
const tempLocalThumbFile = path.join(os.tmpdir(), thumbFilePath);
var folder = fileDir.substr(0, fileDir.indexOf('/'));
if (folder !== 'profile') return null;
if (!contentType.startsWith('image/')) {
console.log('This is not a profile image.');
return null;
}
// if (index === sizes.length - 1) {
// Exit if the image is already a thumbnail.
if (fileName.startsWith(THUMB_PREFIX)) {
console.log('Already a Thumbnail.');
return null;
}
// }
// Cloud Storage files
const bucket = gcs.bucket(object.bucket);
const file = bucket.file(filePath);
const thumbFile = bucket.file(thumbFilePath);
const metadata = {
contentType: contentType,
// To enable Client-side caching you can set the Cache-Control headers here. Uncomment below.
// 'Cache-Control': 'public,max-age=3600',
};
// Create the temp directory where the storage file will be downloaded.
return mkdirp(tempLocalDir).then(() => {
// Download file from bucket.
return file.download({ destination: tempLocalFile });
}).then(() => {
console.log('The file has been downloaded to', tempLocalFile);
// Generate a thumbnail using ImageMagick.
return spawn('convert', [tempLocalFile, '-thumbnail', `${size}x${size}>`, tempLocalThumbFile], { capture: ['stdout', 'stderr'] });
}).then(() => {
console.log('Thumbnail created at', tempLocalThumbFile);
// Uploading the Thumbnail.
return bucket.upload(tempLocalThumbFile, { destination: thumbFilePath, metadata: metadata });
}).then(() => {
console.log('Thumbnail uploaded to Storage at', thumbFilePath);
// Once the image has been uploaded delete the local files to free up disk space.
console.log('Delet tempLocalFile', tempLocalFile)
console.log('Delete tepLocalThumbFile', tempLocalThumbFile)
fs.unlinkSync(tempLocalFile);
fs.unlinkSync(tempLocalThumbFile);
// Get the Signed URLs for the thumbnail and original image.
const config = {
action: 'read',
expires: '03-01-2500',
};
return Promise.all([
thumbFile.getSignedUrl(config),
file.getSignedUrl(config),
]);
}).then((results) => {
const thumbResult = results[0];
const originalResult = results[1];
const thumbFileUrl = thumbResult[0];
const fileUrl = originalResult[0];
// Add the URLs to the Database
...
}).then(() => {
console.log('Thumbnail URLs saved to database. Delete original uploaded image.')
// bucket.file(`/profile/${filename}/${filename}.png`)
// .delete().then(() => console.log('File deleted'))
// .catch(error => console.log(error))
}
).catch(error => console.log(error));
});
});
【问题讨论】:
-
你得到什么样的错误?
if (fileName.startsWith(THUMB_PREFIX))通常不会“导致”任何错误,它只是检查触发云功能的文件是否还不是缩略图。在这种情况下,云函数会停止,因为没有理由处理此文件(因为它已经是缩略图)。 -
没有错误。我不应该说错误。即使创建了缩略图,它也会不断创建更多。我希望它在第二次迭代后停止。
-
您是否修改了示例中的代码?通常它不应该创建更多的缩略图。
-
我确实修改了它。我需要它来创建两个缩略图。一个 200x200 的缩略图和一个 50x50 的缩略图。我还需要它为图像名称添加时间戳。这样图像就会刷新。
-
你的两个缩略图的文件名是什么?
标签: javascript firebase google-cloud-functions firebase-storage