上传图片后。Cloud 函数在 typescript 上使用 sharp 生成相关 firebase 函数中指定的缩略图。但是对于第二张图片等等,缩略图会按预期生成并正确命名,但它包含与上传的第一张图片相同的图片缩略图。
第一张照片: 第一张
第一张照片的缩略图:第一张照片 的缩略图
第二张照片: 默认
第二张照片的缩略图: 默认的缩略图
import * as functions from 'firebase-functions';
import * as Storage from '@google-cloud/storage';
const gcs = Storage();
import { tmpdir } from 'os';
import { join, dirname } from 'path';
import * as sharp from 'sharp';
import * as fs from 'fs-extra';
export const generateThumbs = functions.storage.object().onFinalize(async object => {
const bucket = gcs.bucket(object.bucket);
const filePath = object.name;
const fileName = filePath.split('/').pop();
console.log('filename : ' + fileName);
const bucketDir = dirname(filePath);
const workingDir = join(tmpdir(), 'thumbs');
const tmpFilePath = join(workingDir, 'source.png');
if (fileName.includes('thumb@') || !object.contentType.includes('image')) {
console.log('exiting function');
return false;
}
// 1. Ensure thumbnail dir exists
await fs.ensureDir(workingDir);
// 2. Download Source File
await bucket.file(filePath).download({
destination: tmpFilePath
});
// 3. Resize the images and define an array of upload promises
const sizes = [64, 256, 512];
const uploadPromises = sizes.map(async size => {
const thumbName = `thumb@${size}_${fileName}`;
const thumbPath = join(workingDir, thumbName);
// Resize source image
await sharp(tmpFilePath)
.resize(size, size)
.toFile(thumbPath);
// Upload to GCS
return bucket.upload(thumbPath, {
destination: join(bucketDir, thumbName)
});
});
// 4. Run the upload operations
await Promise.all(uploadPromises);
// 5. Cleanup remove the tmp/thumbs from the filesystem
return fs.remove(workingDir);
});
预期:上传的唯一文件应产生唯一的拇指,而不仅仅是唯一的名称。
实际:仅使用先前图像中的旧拇指数据生成新文件名。