Download a file from NodeJS Server using Express

后端 未结 7 1585
醉梦人生
醉梦人生 2020-11-22 03:10

How can I download a file that is in my server to my machine accessing a page in a nodeJS server?

I\'m using the ExpressJS and I\'ve been trying this:



        
7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 03:44

    Use res.download()

    It transfers the file at path as an “attachment”. For instance:

    var express = require('express');
    var router = express.Router();
    
    // ...
    
    router.get('/:id/download', function (req, res, next) {
        var filePath = "/my/file/path/..."; // Or format the path using the `id` rest param
        var fileName = "report.pdf"; // The default name the browser will use
    
        res.download(filePath, fileName);    
    });
    
    • Read more about res.download()

提交回复
热议问题