多种图像尺寸| Firebase储存

时间:2018-08-10 11:33:59

标签: javascript firebase google-cloud-functions firebase-storage

我正在尝试基于上传的文件创建缩略图,但是我不确定这是否是实现此目的的正确方法。现在,以下代码将继续创建缩略图。 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));
        });
    });

1 个答案:

答案 0 :(得分:0)

从我们上面的评论中看来,您的问题似乎来自以下事实:由于文件名遵循fileName.startsWith(THUMB_PREFIX)模式,因此您无法使用userkey + -size- + timestamp”来检查正确的文件名。

但是,恕我直言,您的代码中还有另一个问题:您使用sizes.forEach((size, index) => {})触发了两次Cloud Function代码。

原始的Cloud Function代码(来自Firebase官方示例)链接了多个异步操作以生成缩略图。原始的Cloud Function代码仅返回一个承诺,该承诺在链的末尾得到解决。

如果要在Cloud Function中执行两次此代码,则应修改承诺链,以便仅返回一个承诺。


您可以按照以下方式进行操作。这只是关于如何复制异步操作​​以并行处理两个文件的非常初步的提案。可能有很大的空间来简化代码-避免重复-并注意,它根本没有经过测试!)

return mkdirp(tempLocalDir)
  .then(() => {
    // Download files from bucket.
    const promises = [];
    promises.push(file_1.download({ destination: tempLocalFile_1 }));
    promises.push(file_2.download({ destination: tempLocalFile_2 }));
    return Promise.all(promises);
  })
  .then(() => {
    const promises = [];
    promises.push(
      spawn(
        'convert',
        [
          tempLocalFile,
          '-thumbnail',
          `${THUMB_MAX_WIDTH_1}x${THUMB_MAX_HEIGHT_1}>`,
          tempLocalThumbFile_1
        ],
        { capture: ['stdout', 'stderr'] }
      )
    );

    promises.push(
      spawn(
        'convert',
        [
          tempLocalFile,
          '-thumbnail',
          `${THUMB_MAX_WIDTH_2}x${THUMB_MAX_HEIGHT_2}>`,
          tempLocalThumbFile_2
        ],
        { capture: ['stdout', 'stderr'] }
      )
    );

    return Promise.all(promises);
  })
  .then(() => {
    //console.log('Thumbnail created at', tempLocalThumbFile);
    // Uploading the Thumbnail.

    const promises = [];
    promises.push(
      bucket.upload(tempLocalThumbFile_1, {
        destination: thumbFilePath_1,
        metadata: metadata
      })
    );
    promises.push(
      bucket.upload(tempLocalThumbFile_1, {
        destination: thumbFilePath_1,
        metadata: metadata
      })
    );
    return Promise.all(promises);
  })
  .then(() => {
    console.log('Thumbnail uploaded to Storage at', thumbFilePath);
    // Once the image has been uploaded delete the local files to free up disk space.
    fs.unlinkSync(tempLocalFile_1);
    fs.unlinkSync(tempLocalThumbFile_1);
    fs.unlinkSync(tempLocalFile_2);
    fs.unlinkSync(tempLocalThumbFile_2);
    // Get the Signed URLs for the thumbnail and original image.
    const config = {
      action: 'read',
      expires: '03-01-2500'
    };
    return Promise.all([
      thumbFile_1.getSignedUrl(config),
      file_1.getSignedUrl(config),
      thumbFile_2.getSignedUrl(config),
      file_2.getSignedUrl(config)
    ]);
  })
  .then(results => {....}}

此外,我建议您观看Firebase视频系列中有关“ JavaScript承诺”的3个视频:https://firebase.google.com/docs/functions/video-series/