不为别的,只为做一个连自己都羡慕的人

使用node,实现文件的下载功能

// 文件下载  将pdf文件转为流的形式,传到前端,实现下载功能
router.get('/downloadFile',(req,res)=>{
    let { id } = req.query;
    // var path="public/pdf/5ea56710fb5a2fdad7cabcf3.pdf";
    var path=`public/pdf/${id}.pdf`;
    var fileStream = fs.createReadStream(path);
    res.setHeader('Content-type', 'application/octet-stream');
    // res.setHeader('Content-Disposition', 'attachment;filename=1.pdf'); 
    res.setHeader('Content-Disposition', `'attachment;filename=${id}.pdf'`); 
    fileStream.on('data', function (data) {
        res.write(data, 'binary');
    });
    fileStream.on('end', function () {
        res.end();
        console.log('The file has been downloaded successfully!');
    });
})

 

posted @ 2020-07-11 13:54  升级打怪  阅读(2421)  评论(0编辑  收藏  举报