【问题标题】:database triggers firebase function to download images from URL and save it to storage数据库触发 firebase 函数从 URL 下载图像并将其保存到存储中
【发布时间】:2017-11-03 03:57:04
【问题描述】:

当我的数据库使用“photo_url”字段更新时,我想下载图像并将其保存到存储中

exports.saveToStorage = functions.database.ref(`/images/${itemImageRef}`)
.onWrite(event => {
  const filePath = event.data.val();
  const filename = filePath.split('/').pop();

  var download = request.get(filePath).on('error', (err) => {
    console.log(err)
  })
  .pipe(fs.createWriteStream(filename));

  download.on('finish', () => {
    const bucket = gcs.bucket('id.appspot.com');
    const storagePath = `images/${filename}`;

    return bucket.upload(download, { destination: storagePath })
    .then(() => {
      console.log('success upload');
    });
  });
});

它记录“错误:EROFS:只读文件系统,在错误(本机)处打开'image.jpg'。”我想我无法检索 createWriteStream 保存的文件? 那么我应该如何从网络上下载图像呢?

【问题讨论】:

  • 也许这会对你有所帮助:stackoverflow.com/q/43698405/3366109
  • 谢谢,但我已经升级了我的计划,所以它应该能够发出外部请求。
  • @Jobsamuel,我忽略了解决方案,代码有帮助,我现在可以将数据通过管道传输到 Firebase 存储,它跳过了在我原来的方法中使用 fs“本地”存储文件的步骤。 Firebase 函数现在能够将文件保存到存储中,但它仍然无法识别它是图像。也许我必须更改元数据 contentType 中的设置。

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


【解决方案1】:

根据@Jobsamuel 建议的帖子,代码现在可以工作了:

exports.saveToStorage = functions.database.ref(`/images/${itemImageRef}`)
.onWrite(event => {

  const filePath = event.data.val();
  const filename = filePath.split('/').pop();

  const bucket = gcs.bucket('id.appspot.com');
  const remoteWriteStream = bucket.file(filename).createWriteStream({
    metadata: { contentType: 'image/jpeg' }
  });

  request(filePath).pipe(remoteWriteStream)
  .on('error', (err) => console.log(err))
  .on('finish', () => console.log('success save image'));

});

通过将请求结果直接通过管道传输到存储桶,它通过跳过写入本地文件的步骤来解决问题,我怀疑这是我的原始代码失败的原因。另外,不要忘记为图片设置 contentType。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    • 2019-05-07
    • 1970-01-01
    • 2018-12-29
    相关资源
    最近更新 更多