将谷歌云存储中的文件直接下载到nodejs中的客户端

Boy*_*era 5 download node.js google-cloud-storage

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

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}`
    });
  }
});

Run Code Online (Sandbox Code Playgroud)

Sho*_*oom 6

这在 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);
   });}
Run Code Online (Sandbox Code Playgroud)