从API下载pdf文件 [英] Download pdf file from API

查看:67
本文介绍了从API下载pdf文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个函数,可在单击按钮后创建并下载pdf.我使用express作为后端,而react/readux/axios作为前端.

I am creating a function that creates and download a pdf after button click. I am using express as backend and react/readux/axios as front.

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

My backend runs on a different port than my front.

因此,我要使用axios调用API,然后表示创建pdf并使用sendFile进行响应.

So I am calling the API with axios, then express create the pdf and respond with sendFile.

与邮递员一起测试我的发帖请求时,一切正常.

When testing my post request with postman everything works great.

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

When i using it from my react app does not download the file

表达

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')
    })
}

推荐答案

仅在'GET'请求的情况下下载文件.您只需简单地创建一个接受'GET'请求的API.在客户端,您可以通过以下操作调用 window.open(带有api路径的服务器完整网址").

The download for a file works only in case of 'GET' request. You can simply simply make a API that accepts a 'GET' request. And from client side, on some action You can call window.open('server full url with api path').

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

By doing above the it start downloading your file.

这篇关于从API下载pdf文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆