簡體   English   中英

如何使用瀏覽器下載管理器從 express + mongoDB 服務器下載/流式傳輸文件

[英]How to download/stream a file from a express + mongoDB server, using the browser download manager

所以我的標題可能沒有多大意義,所以讓我解釋一下,我正在使用 express 和 mongoose/MongoDB 來上傳/下載文件,然后我可以將 go 發送到瀏覽器 URL 並提供這樣的獲取文件請求,但是我wanted to add authentication, and since I need to send a JWT token through the header, I am unable to just go to the URL through the browser, let me show you what I have so far.

router.get('/file-service/download', auth, async (req, res) => {
  if (!req.user) {
    return res.status(401).send('Please authenticate');
  }

  try {
    const tempID = '5dc5f57a081263451cee80d4';

    const gfs = Grid(conn.db);

    gfs.findOne({ _id: tempID }, (err, file) => {
      //console.log("file", file);

      if (err) {
        return res.status(500).send(err);
      }

      res.set('Content-Type', file.contentType);
      res.set('Content-Disposition', 'attachment; filename="' + file.filename + '"');

      const readStream = gfs.createReadStream({
        _id: tempID
      });

      //console.log("grid", readStream);

      readStream.pipe(res);
    });
  } catch (e) {
    console.log(e);
    res.status(500).send(e);
  }
});

所以我使用 go 到 localhost:3000/file-service/download,它只會在 chrome 中開始下載,使用本機下載管理器,並顯示進度,下載文件時你期望的一切,但現在這是不可能,所以我改為執行axios請求,而不是像這樣。

const config = {
  responseType: 'arraybuffer',
  headers: { Authorization: 'Bearer ' + 'jwtsecret' }
};

console.log('fetching download');

axios
  .get('http://' + currentURL + '/file-service/download', config)
  .then(response => {
    let blob = new Blob([response.data], { type: 'binary/octet-stream' });
    let link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = 'zip_test.zip';
    link.click();
  })
  .catch(err => {
    console.log(err);
  });

這有效,但是,它必須首先將整個文件加載到 memory 中,例如,我用 500mb 文件測試這個,在我執行axios請求之后,它需要 15 多秒才能獲取所有數據,然后它會提示使用下載並立即完成。 但是,如果我刪除身份驗證,並通過瀏覽器通過 URL 執行此操作,下載會立即開始並像往常一樣顯示 chrome 下載的進度。 有什么方法可以使用axios實現這種相同的下載/流媒體功能? 或者有什么方法可以在沒有axios的情況下發送令牌,這樣我就可以完全避免它並以正常方式進行操作?

您可以將令牌作為查詢而不是中間件傳遞,即http://localhost:3000/file-service/download?token=kjhdsjkf.sakhdh.asdkd並在用戶繼續下載之前驗證令牌

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM