Firebase 云函数存储触发器第一个缩略图网址很好,然后下一个都是与第一个相同的缩略图网址



我正在尝试将图像上传到Firebase,然后生成2个缩略图。我能够毫无问题地做到这一点。我目前的障碍是当我将 url 写入实时数据库时,我总是得到与初始上传相同的 url。

例如:

    第一次上传 我
  • 得到了我上传的图像,其中包含图像的两个正确缩略图
  • 第二次上传,我得到了我上传的图像和前两个缩略图(第一张图片(
  • 第三次上传我
  • 得到了我上传的图像,带有第一个图像缩略图.........这将继续重现第一次上传的 URL

在我的存储中,正在生成正确的缩略图,但网址始终用于首次上传?

我不知道这是否是getSignedUrl((的问题,真的不确定这里发生了什么。

这是我的云函数:

  export const generateThumbs = functions.storage
    .object()
    .onFinalize(async object => {
    const bucket = gcs.bucket(object.bucket); // The Storage object.
    // console.log(object);
    console.log(object.name);
    const filePath = object.name; // File path in the bucket.
    const fileName = filePath.split('/').pop();
    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 Sounrce fileName
    await bucket.file(filePath).download({
      destination: tmpFilePath
    });
    //3. resize the images and define an array of upload promises
    const sizes = [64, 256];
    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),
        metadata: {
         contentType: 'image/jpeg'
       }
      }).then((data) => {
        const file = data[0]
        // console.log(data)
        file.getSignedUrl({
          action: 'read',
          expires: '03-17-2100'
        }).then((response) => {
          const url = response[0];
          if (size === 64) {
            // console.log('generated 64');
            return admin.database().ref('profileThumbs').child(fileName).set({ thumb: url });
          } else {
            // console.log('generated 128');
            return admin.database().ref('categories').child(fileName).child('thumb').set(url);
          }
        })
        .catch(function (error) {
          console.error(err);
          return;
        });
      })
    });
    //4. Run the upload operations
    await Promise.all(uploadPromises);
    //5. Cleanup remove the tmp/thumbs from the filesystem
    return fs.remove(workingDir);
  })

清理了我的代码并解决了我的问题,以下是我如何通过访问文件路径中的用户 UID 和 postId 来生成 url 并将它们传递给正确的 URL:

export const generateThumbs = functions.storage
.object()
.onFinalize(async object => {
    const fileBucket = object.bucket; // The Storage bucket that contains the file.
    const filePath = object.name; // File path in the bucket.
    const fileName = filePath.split('/').pop();
    const userUid = filePath.split('/')[2];
    const sizes = [64, 256];
    const bucketDir = dirname(filePath);
    console.log(userUid);
    if (fileName.includes('thumb@') || !object.contentType.includes('image')) {
        console.log('exiting function');
        return false;
      }
    const bucket = gcs.bucket(fileBucket);
    const tempFilePath = path.join(tmpdir(), fileName);
    return bucket.file(filePath).download({
      destination: tempFilePath
    }).then(() => {
     sizes.map(size => {      
        const newFileName = `thumb@${size}_${fileName}.png`
        const newFileTemp = path.join(tmpdir(), newFileName);
        const newFilePath = `thumbs/${newFileName}`
        return sharp(tempFilePath)
          .resize(size, size)
          .toFile(newFileTemp, () => {
            return bucket.upload(newFileTemp, {
                destination: join(bucketDir, newFilePath),
                metadata: {
                    contentType: 'image/jpeg'
                  }
            }).then((data) => {
                const file = data[0]
                console.log(data)
                file.getSignedUrl({
                  action: 'read',
                  expires: '03-17-2100'
                }, function(err, url) {
                    console.log(url);
                  if (err) {
                    console.error(err);
                    return;
                  }
                  if (size === 64) {
                    return admin.database().ref('profileThumbs').child(userUid).child(fileName).set({ thumb: url });
                  } else {
                    return admin.database().ref('categories').child(fileName).child('thumb').set(url);
                  }
                })
              })
          })
      })
    }).catch(error =>{
        console.log(error);
      });
  })

最新更新