Calling Spring boot api that downloads a pdf from Angular 6 is giving error can't parse response

送分小仙女□ 提交于 2019-12-06 03:39:01

To avoid the JSON parsing issue, you need to tell the http client that the response will be a blob, using responseType: 'blob' in requests options.

Then, to actually have the navigator open the file, you can follow the instructions from this blog

    const fileName = "report.pdf";
    this.http.get(this.api_url + reportUrl, {  responseType: 'blob'})
    .subscribe((blob: Blob) => {
    console.log('report is downloaded');

    if (navigator.msSaveBlob) 
    { 
        // IE 10+
        navigator.msSaveBlob(blob, filename);
    }
    else 
    {
        let link = document.createElement("a");
        if (link.download !== undefined) 
        {
            let url = URL.createObjectURL(blob);
            link.setAttribute("href", url);
            link.setAttribute("download", fileName);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        else
        {
            //html5 download not supported
        }
    }   
});

This should work for IE 10+ and other modern browsers, apart from iOs (see CanIuse)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!