上传图像后。Cloud函数使用sharp on typescript生成相关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);
});
预期:上传的唯一文件应该产生唯一的拇指,而不仅仅是唯一的名称。
实际:只有新的文件名是用以前图像中的旧拇指数据生成的。
我认为这是一个缓存问题。。我通过在tmp文件夹中使用uuid添加了一个解决方法。因此,不可能再存在任何缓存文件了。
安装uuid包
npm i uuid
将其作为全局导入
import { Storage } from '@google-cloud/storage';
const gcs = new Storage();
const uuidv1 = require('uuid/v1');
并将workinDir行更改为:
const workingDir = join(tmpdir() + '/' + uuidv1(), 'thumbs');