【问题标题】:Upload file to cloud storage using firebase cloud functions使用 Firebase 云功能将文件上传到云存储
【发布时间】:2017-12-21 14:25:31
【问题描述】:

我正在检查这个示例代码:

// Download file from bucket.
const bucket = gcs.bucket(fileBucket);
const tempFilePath = path.join(os.tmpdir(), fileName);
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});
// Once the thumbnail has been uploaded delete the local file to free up disk space.
}).then(() => fs.unlinkSync(tempFilePath));

我的问题具体在这一行:

return bucket.upload(tempFilePath, {destination: thumbFilePath});

为什么我们在这里提供destination 参数的完整文件路径?据我了解,destination 参数表示上传到存储桶后将采用的文件名。

所以我的猜测是 "thumb_Qsdflsdfa.png" 就足够了,而不是 "/tmp/../thumb_Qsdflsdfa.png"

【问题讨论】:

    标签: firebase google-cloud-storage google-cloud-functions


    【解决方案1】:

    根据文档here,第二个参数是可选的。

    如果您不介意图像名称与存储桶中的文件名相同,则可以将其留空。例如-

    bucket.upload('/local/path/image.png') - 您的存储桶名称将是 image.png

    但是,如果你想根据你的项目命名其他有意义的东西,你可以传入第二个参数,像这样 -

    bucket.upload('/local/path/image.png', { destination: 'thumb_image.png' }) - 您的存储桶名称现在将是 thumb_image.png

    希望这是有道理的。

    这里有一张截图让大家更清楚-

    【讨论】:

    • 权限问题?问题没有说明许可
    • 哦,对不起,我有两个类似的问题,我以为你回答了另一个;好的,谢谢您的解释,我认为您的回答很有意义,但是在代码上,他们将完整的文件路径作为目标参数传递,而不仅仅是文件名。有什么想法吗?
    • 哈哈,不用担心。所以我做了一个快速测试,看起来path.join(path.dirname(filePath), thumbFileName); 只给了我们文件名thumb_image.png 而不是myFolder/thumb_image.png,它确实将它正确地存储在myFolder/ 中。所以要回答你的问题,在这个例子中,你需要它来定义你希望它存储的位置,但它所采用的名称将是文件名而不是整个路径名。
    • 所以整个path.join(path.dirname(filePath), thumbFileName) 和 thumbFileName 一样?
    • 对不起,我可能误解了,值是myFolder/thumb_image.png,它用thumb_image.png 名称将它保存在myFolder 中。为了清楚起见,我放了一张图片,看看。
    猜你喜欢
    • 2018-11-17
    • 2021-10-28
    • 2021-04-21
    • 2019-06-23
    • 2019-08-08
    • 1970-01-01
    • 2021-03-07
    • 2020-07-05
    • 2017-12-19
    相关资源
    最近更新 更多