简体   繁体   English

Mongodb和Gridfs文件下载

[英]Mongodb and Gridfs file download

I'm building an application that allows the user to upload and download files.我正在构建一个允许用户上传和下载文件的应用程序。 The issue i'm currently having is that I can retrieve the file from my MongoDB database and download it locally through my machine, but I can't get it to download through the browser.我目前遇到的问题是我可以从我的 MongoDB 数据库中检索文件并通过我的机器将其下载到本地,但我无法通过浏览器下载它。

So far I have tried doing it like this到目前为止,我试过这样做

const conn = mongoose.createConnection(process.env.URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true
})

const bucket = new GridFSBucket(conn, {bucketName: 'uploads'});


router.get('/download', (req, res) => {

    const files = bucket.openDownloadStreamByName('3987a162969935378c4f8cbe5d95bb46.svg').pipe(fs.createWriteStream('./3987a162969935378c4f8cbe5d95bb46.svg'))
    res.end()
})

I do not think the issue is with mongoDB or Gridfs its how you are dealing with the file stream. If you want the file to be downloaded once the user calls /GET /download you need to我认为问题不在于 mongoDB 或 Gridfs,它是您处理文件 stream 的方式。如果您希望在用户调用 /GET /download 后下载文件,您需要
use - res.download(file);使用 - res.download(file); eg例如

 const conn = mongoose.createConnection(process.env.URL, { useNewUrlParser: true, useUnifiedTopology: true }) const bucket = new GridFSBucket(conn, { bucketName: 'uploads' }); router.get('/download', (req, res) => { const files = bucket.openDownloadStreamByName('3987a162969935378c4f8cbe5d95bb46.svg').pipe(fs.createWriteStream('./3987a162969935378c4f8cbe5d95bb46.svg')) res.download(files) })

Good Luck!祝你好运! Also visit this Download a file from NodeJS Server using Express另请访问此使用 Express 从 NodeJS 服务器下载文件

If we want to send file directly to client without writing to disk, use this:如果我们想直接将文件发送到客户端而不写入磁盘,请使用:

backend后端

router.get('/download', (req, res) => {
  res.set('Content-disposition', `attachment; filename="your_file_name.svg"`);
  res.set('Content-Type', 'image/svg+xml');
  bucket.openDownloadStreamByName('your_file_name.svg').pipe(res);
})

frontend前端

fetch('http://localhost:8000/download')
      .then(res => res.blob())
      .then(data => {
        saveAs(data, 'your_file_name.svg');
      })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM