代码之家  ›  专栏  ›  技术社区  ›  Ciprian

多种图像大小| Firebase存储

  •  0
  • Ciprian  · 技术社区  · 8 年前

    我正在尝试根据上传的文件创建缩略图,但我不确定这是否是实现此目的的正确方法。下面的代码继续创建缩略图。 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 回复  |  直到 8 年前
        1
  •  0
  •   Renaud Tarnec    8 年前

    从我们上面的评论来看,您的问题似乎是因为您“没有检查正确的文件名” fileName.startsWith(THUMB_PREFIX) userkey + -size- + timestamp 模式。

    但是,在代码中还有一个问题:您正在使用 sizes.forEach((size, index) => {})

    原始的云函数代码(来自Firebase官方示例)链接了几个异步操作,以便生成缩略图。原始的云函数代码只返回一个承诺,即在链的末尾解析的承诺。


    你可以沿着这条路线做点什么。这只是一个 提案初稿 关于如何复制异步操作以并行处理这两个文件。可能有很大的空间来简化代码—避免重复—请注意,它根本没有经过测试!)

    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 => {....}}
    

    https://firebase.google.com/docs/functions/video-series/