Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

node.js - Cloud Functions: Resized images not loading

I am following a tutorial to resize images via Cloud Functions on upload and am experiencing two major issues which I can't figure out:

1) If a PNG is uploaded, it generates the correctly sized thumbnails, but the preview of them won't load in Firestorage (Loading spinner shows indefinitely). It only shows the image after I click on "Generate new access token" (none of the generated thumbnails have an access token initially).

2) If a JPEG or any other format is uploaded, the MIME type shows as "application/octet-stream". I'm not sure how to extract the extension correctly to put into the filename of the newly generated thumbnails?

export const generateThumbs = functions.storage
.object()
.onFinalize(async object => {
  const bucket = gcs.bucket(object.bucket);
  const filePath = object.name;
  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 Source File
 await bucket.file(filePath).download({
   destination: tmpFilePath
 });

// 3. Resize the images and define an array of upload promises
 const sizes = [64, 128, 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)
  });
});

// 4. Run the upload operations
  await Promise.all(uploadPromises);

// 5. Cleanup remove the tmp/thumbs from the filesystem
  return fs.remove(workingDir);
  });

Would greatly appreciate any feedback!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...