Node.js express 实现文件下载,前端使用window.open

77 阅读1分钟

接口代码

const request = require('request-promise')


router.post('/test/iamges/download', (req, res, next) => {
    const uri = `http://127.0.0.1:8080/images/test.png`;
    const fileName = '测试图片'
    const options = {
        url: uri,
        gzip:true,
        headers:{
            'Content-Type': 'application/octet-stream'
        },
    }
    request.get(options).on('response', function(response) {
       // 给下载的文件重命名, 经过测试,起作用的应该是这句代码
       response.headers['Content-Disposition'] = `attachment;filename=${encodeURIComponent(fileName)}`;
       // 下边这一句好像不起作用
       res.setHeader('Content-Disposition', `attachment;filename=${encodeURIComponent(fileName)}`;
        this.pipe(res);
    });
})

前端页面代码

window.open('http://127.0.0.1:8080/test/iamges/download')