【问题标题】:Download file from google cloud storage directly to client in nodejs将文件从谷歌云存储直接下载到nodejs中的客户端
【发布时间】:2020-07-20 17:46:42
【问题描述】:

我希望能够将从谷歌云下载的文件直接发送到客户端,而不必先保存在我的服务器上,然后从我服务器上保存的版本创建一个下载到客户端,因为这会使过程变慢,因为文件被下载了两次,首先从谷歌云到我自己的服务器,然后从我自己的服务器到客户端。

router.get("/:filename", async(req, res) => {
  try {
    // Grab filename from request parameter
    const fetchURL =req.params.filename;
    const file = await File.findOne({fetchURL});
    const srcFileName = file.originalname;
  // Call GCS with bucketName and check the file method with srcFileName and check again with download method which takes download path as argument
    storage
      .bucket(bucketName)
      .file(srcFileName)
      .download({
        destination: path.join(process.cwd(), "downloads", srcFileName)
      })
      .then(() =>
        res.download(path.join(process.cwd(), "downloads", srcFileName), err =>
          err ? console.log(err) : null
        )
      )
      .catch(err =>res.status(400).json({
        message: err.message
      }));
  } catch (err) {
    res.status(res.statusCode).json({
      message: `There was an error downloading your file. ${err.message}`
    });
  }
});

【问题讨论】:

  • 如果您不喜欢在将文件提供给公众之前将其下载到服务器中,另一种选择是使用Signed URLs,它可以为任何人提供有时间限制的资源访问权限,无论是否他们有一个谷歌帐户。 Here 您还会发现如何轻松生成这些签名的 URL 并将它们传递给用户,在您的情况下是客户端,而无需将文件下载到您的服务器中。我希望它有所帮助。
  • 谢谢@ChristopherRodriguezConde,你说得非常对,我确实在文档中发现了这一点,因为我在几个小时后无法得到任何回复,所以我所做的是生成有效的签名 URL 并发送到客户。
  • 我的组织政策禁止公开访问 url。一定有办法直接在程序中获取文件内容?

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


【解决方案1】:

这适用于 NodeJS+Express 服务器:

const {Storage} = require('@google-cloud/storage');
const storage = new Storage({projectId, keyFilename}); 

router.get('/:id', async function (req, res) {

   let fileName = 'test.jpg'; //For example
   let contetType = 'image/jpg;' //For example
   res.writeHead(200, {
    'Content-Disposition': `attachment;filename=${filename}`,
    'Content-Type': `${contetType}`
   });

   await storage
   .bucket('my-bucket')
   .file(`Images/${req.params.id}/${filename}`)
   .createReadStream() //stream is created
   .pipe(res);
   });

【讨论】:

    猜你喜欢
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 2017-11-23
    • 2019-05-08
    • 2021-01-14
    相关资源
    最近更新 更多