【问题标题】:How to properly set response headers when streaming download of an image from Google Cloud Storage从 Google Cloud Storage 流式下载图像时如何正确设置响应标头
【发布时间】:2019-06-09 01:48:09
【问题描述】:

到目前为止我有这个:

app.get('/:image/:size.:ext', (req, res) => {
  const remote = bucket.file(`${req.params.image}/${req.params.size}.${req.params.ext}`)
  if (req.query.download == 'true') {
    res.set('Content-Type', 'image/jpg')
    res.set('Content-Disposition', `attachment; filename="${req.params.image}.${req.params.size}.${req.params.ext}";` )
    res.set('Content-Transfer-Encoding', 'binary')
    // header("Content-Length: ".filesize($filename))
  }
  // if (isProd)
  //   res.set('Cache-Control', 'public, max-age=604800')
  remote.createReadStream({ validation: false })
    .on('error', error => {
      console.log(error)
      res.send(`data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7`)
    })
    .pipe(res)
})

在那个download=true 块中,我不确定如何获取文件大小,如果它以某种方式通过remote 流传递,或者我是否应该将它存储在某个数据库中,或者以某种方式获取。

【问题讨论】:

标签: node.js image google-cloud-platform download google-cloud-storage


【解决方案1】:

您可以从 getMetadata(options, callback) 获取 metadata.size,它返回包含 GetFileMetadataResponse 的 Promise

storage
  .bucket(bucketName)
  .file(filename)
  .getMetadata()
  .then(results => {
    const metadata = results[0];

    console.log(`File: ${metadata.name}`);
    console.log(`Size: ${metadata.size}`);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 2018-06-06
    • 1970-01-01
    • 2014-01-18
    • 2016-04-13
    相关资源
    最近更新 更多