node.js - 如何使用云功能制作缩略图并将其放置在 Firebase 存储中的特定文件夹中?

标签 node.js firebase google-cloud-storage google-cloud-functions firebase-storage

这里有一个来自 firebase 的示例代码,介绍如何创建缩略图:

https://github.com/firebase/functions-samples/blob/master/quickstarts/thumbnails/functions/index.js

代码是这样的

// [START import]
const functions = require('firebase-functions');
const gcs = require('@google-cloud/storage')();
const spawn = require('child-process-promise').spawn;
const path = require('path');
const os = require('os');
const fs = require('fs');
// [END import]

// [START generateThumbnail]
/**
 * When an image is uploaded in the Storage bucket We generate a thumbnail automatically using
 * ImageMagick.
 */
// [START generateThumbnailTrigger]
exports.generateThumbnail = functions.storage.object().onFinalize((object) => {
// [END generateThumbnailTrigger]
  // [START eventAttributes]
  const fileBucket = object.bucket; // The Storage bucket that contains the file.
  const filePath = object.name; // File path in the bucket.
  const contentType = object.contentType; // File content type.
  const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1.
  // [END eventAttributes]

  // [START stopConditions]
  // Exit if this is triggered on a file that is not an image.
  if (!contentType.startsWith('image/')) {
    console.log('This is not an image.');
    return null;
  }

  // Get the file name.
  const fileName = path.basename(filePath);
  // Exit if the image is already a thumbnail.
  if (fileName.startsWith('thumb_')) {
    console.log('Already a Thumbnail.');
    return null;
  }
  // [END stopConditions]

  // [START thumbnailGeneration]
  // Download file from bucket.
  const bucket = gcs.bucket(fileBucket);
  const tempFilePath = path.join(os.tmpdir(), fileName);
  const metadata = {
    contentType: contentType,
  };
  return bucket.file(filePath).download({
    destination: tempFilePath,
  }).then(() => {
    console.log('Image downloaded locally to', tempFilePath);
    // Generate a thumbnail using ImageMagick.
    return spawn('convert', [tempFilePath, '-thumbnail', '200x200>', tempFilePath]);
  }).then(() => {
    console.log('Thumbnail created at', tempFilePath);
    // We add a 'thumb_' prefix to thumbnails file name. That's where we'll upload the thumbnail.
    const thumbFileName = `thumb_${fileName}`;
    const thumbFilePath = path.join(path.dirname(filePath), thumbFileName);
    // Uploading the thumbnail.
    return bucket.upload(tempFilePath, {
      destination: thumbFilePath,
      metadata: metadata,
    });
    // Once the thumbnail has been uploaded delete the local file to free up disk space.
  }).then(() => fs.unlinkSync(tempFilePath));
  // [END thumbnailGeneration]
});
// [END generateThumbnail]

但是尝试上面的代码后,创建的缩略图似乎位于与原始图像(个人资料图像)相同的文件夹中,如下图所示

enter image description here

如果我希望缩略图位于名为“thumbnail”的不同文件夹中,该怎么办?因此,如果将图像上传到“profileImage”文件夹,缩略图将被放置到“thumbnail”文件夹

enter image description here

最佳答案

您需要修改的代码在这里:

const thumbFileName = `thumb_${fileName}`;
const thumbFilePath = path.join(path.dirname(filePath), thumbFileName);
// Uploading the thumbnail.
return bucket.upload(tempFilePath, {
  destination: thumbFilePath,
  metadata: metadata,
});

它正在构建一条指向 Cloud Storage 中文件应在 thumbFilePath 中上传的位置的路径。您可以看到它加入了 filePath 目录和文件名 thumbFileNamefilePath 被定义为原始文件开头的位置:

const filePath = object.name; // File path in the bucket.

所有这意味着无论原始文件上传到哪里,缩略图都会排列在它旁边。

如果您想更改最终缩略图的位置,请使 thumbFilePath 包含该位置。它可能就像这样简单地改变它:

const thumbFilePath = `thumbnail/${thumbFileName}`

或者任何你需要的东西。

关于node.js - 如何使用云功能制作缩略图并将其放置在 Firebase 存储中的特定文件夹中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52254702/

相关文章:

angular - Firestore 在 Angular 2 上按 id 获取文档

ios - CloudStorageTools::serve() 音频无法在 iOS 上播放

google-cloud-storage - 将 Google Cloud Storage 存储分区移动到另一个项目

javascript - Firebase 推送 - 删除唯一对象并插入新对象(基本上覆盖内容)

javascript - 将用户推送到数组时,会创建多个数组

node.js - postgres 中的大量数据库 - 架构最佳实践

node.js - Angular Js 意外 token 错误动态路由

java - Firebase实时数据库: How to use onDisconnect

python - Google Cloud Storage/Big Query 成本估算

javascript - node.js 开发人员的高级文档