Node——设置响应报文头实现下载

基本介绍

  • 实现下载一般就是通过浏览器点击下载

  • 后台一般设置一下响应头,有下面两种方式

    • Content-Type
    • Content-Disposition

Content-Type

  • res.setHeader('Content-Type', 'application/octet-stream')
  • 此设置提示浏览器这是一个字节流,浏览器默认会弹出让客户进行下载

Content-Disposition

  • res.setHeader('Content-Disposition', 'inline;filename=hello.md')

  • inline,提示浏览器从页面打开文件内容;attachment,是提示浏览器弹出下载

  • filename,是自定义文件名

    app.use('/files', function (req, res) {
        var filename = path.join(__dirname, 'files', req.url);
        //res.setHeader('Content-Type', 'application/octet-stream')
        res.setHeader('Content-Disposition', 'inline;filename=hello.md')
        res.sendfile(filename);
    })
    
原文地址:https://www.cnblogs.com/cnloop/p/9304757.html