从API下载pdf文件

时间:2017-11-29 04:27:41

标签: reactjs express redux axios

我正在创建一个在按钮点击后创建和下载pdf的功能。我使用express作为后端,并将react / readux / axios作为前端。

我的后端运行在与我前面不同的端口上。

所以我用axios调用API,然后表达创建pdf并用sendFile响应。

当用邮递员测试我的帖子请求时,一切都很好。

当我在我的反应应用程序中使用它时,不会下载文件

表达

router.post('/', function( req, res, next){

var data = req.body.data

options = {};
// init html string
var html = ejs.renderFile(__dirname + '/template/facture.ejs',  {data: data}, options, function(err, str){
    if(err){
        return err;
    }
    return str;
});
// create pdf
conversion({ html: html}, (err, pdf) => {
    var output = fs.createWriteStream(`documents/factures/${data.Référence}.pdf`);
    pdf.stream.pipe(output);

});

var filepath = path.join(pathToDocument, '/factures/',`${data.Référence}.pdf`);

res.download(filepath);

});

Axios致电

export function generatePdf(data){
return dispatch => {

    axios.post(`${API_ENDPOINT}api/facture-pdf`,
        { data: data },
        { headers: {
            'Content-Type': 'application/json',
            'x-access-token': localStorage.getItem('token')
        }
    })
    .then(function (response) {  
        return response.data;
    }) 
    .then( pdf => {
        window.open(`${API_ENDPOINT}api/${type}-pdf/${data.Référence}`, '_blank')
    })
}

1 个答案:

答案 0 :(得分:0)

文件下载仅适用于'GET' request。 您只需创建一个接受'GET' request的API即可。 从客户端来看,在某些操作上您可以致电window.open('server full url with api path')

通过上面的操作开始下载文件。