【问题标题】:Thumbnail generated from first image is duplicated for others on Firebase storage从第一个图像生成的缩略图在 Firebase 存储中为其他图像复制
【发布时间】:2019-05-27 22:20:50
【问题描述】:

上传图片后。 Cloud 函数在 typescript 上使用 sharp 生成相关 firebase 函数中指定的缩略图。但是对于第二张图片等等,缩略图会按预期生成并正确命名,但它包含与上传的第一张图片相同的图片缩略图。

第一张照片: First

第一张照片的缩略图: thumb of first

第二张照片: default

第二张照片的缩略图: thumb of default

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);
});

预期:上传的唯一文件应生成唯一的拇指,而不仅仅是唯一的名称。

实际:仅使用先前图像中的旧拇指数据生成新文件名。

【问题讨论】:

  • 你所有的图片都有这个错误:>{ "error": { "code": 403, "message": "Permission denied. Could not perform this operation" } }
  • @MosheSlavin 现已上市。
  • 你解决了吗?我有同样的问题。对我来说,文件被覆盖了,我怀疑这可能是问题所在。这也和你的场景一样吗?

标签: firebase google-cloud-storage google-cloud-functions image-resizing sharp


【解决方案1】:

我认为这是一个缓存问题。我通过在 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');

【讨论】:

    猜你喜欢
    • 2017-01-19
    • 2011-01-27
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-21
    • 2016-04-09
    相关资源
    最近更新 更多