Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 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 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...