1

I'm using springboot backend api to download a pdf file with react frontend. When the backend api is tested on postman, it asks to download the response, and the expected pdf gets downloaded. When I integrate the api with react, it shows the following in the response,

%PDF-1.4 %���� 2 0 obj <>stream x����n�0��~ �Ò�M����ay�I��P��ɲk���Kٰb�d�"?�����v�N��p������N�o: ��O��ӏ��z:��D &����#����"�[�Gпr�� r�[��ƽ�EM ���ać�����E�Pw��3Dn1�ض���"qr����2�B �Rz���E�ɕl�b6�?H`��T搵�DS��;�Zh�&�ƅ�J.s*i���H��fX�ʪ��6�(��x=w߻�� endstream endobj 4 0 obj <>>>/Contents 2 0 R/Parent 3 0 R>> endobj 1 0 obj <> endobj 3 0 obj <> endobj 5 0 obj <> endobj 6 0 obj <> endobj xref 0 7 0000000000 65535 f 0000000590 00000 n 0000000015 00000 n 0000000676 00000 n 0000000478 00000 n 0000000727 00000 n 0000000772 00000 n trailer <<2324328368ff9e8a10923bbe7a3d048d>]>> %iText-5.5.13.1 startxref 1020 %%EOF

but never gets downloaded. So I found these solutions, which require the response type='blob' https://stackoverflow.com/a/47079123/10598769 -This solution downloads me only a blank pdf. https://stackoverflow.com/a/41940307/10598769 -Downloads a blank pdf as well

enter image description here

However, if I try on postman as said earlier, the pdf downloaded is not blank.

Please help me with a workaround for this. Any help is appriciated.

Front end code; From service class-i've used 'file-saver' here. but I've tried other options here the same way.

const downloadarticle=createLogic({
    type:downloadArticleTypes.DOWNLOAD_ARTICLE,
    latest:true,
    debounce:1000,

    process({
        action
    },dispatch,done){
        let HTTPclient=api

        // debugger
        console.log("payload check",action.payload)

        let obj={
            generatedText:action.payload.generated_text,
        }

        HTTPclient.postPDF(endPoints.DOWNLOAD_ARTICLE+"/"+action.payload.article_id,obj)
            .then(resp=> {
                // debugger
                console.log(resp.data)

                var blob = new Blob([resp.data], {type: "application/pdf"});
                saveAs(blob, resp.data.filename)

            })
            .catch(err=>{
                var errormsg="Failed to download Article";
                if (err && err.code === "ECONNABORTED") {
                    errormsg = "Please check your internet connection.";
                }
                dispatch(downloadArticleActions.DdownloadArticleFail(errormsg))
            }).then(()=>done());
    }
})

HttpClient class code for the post

export const postPDF=(route,imgdata,responseType='blob')=>{
    instance || setAuth()
    return instance.post(route,imgdata,responseType)
    // dtodata == null ? { dtodata: {} } : dtodata= JSON.stringify(dtodata),
}

on the component, I call the action, on Download button click as follows

 onDownloadClick=()=>{
        let obj={
            article_id:0,
            generated_text:this.state.item.caption
        }

        this.props.downloadArticleActions.downloadArticle(obj)
    }

Backend API implementation; Controller

@RequestMapping(value = "/download/{id}", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_PDF_VALUE)
    public ResponseEntity<?> downloadArticle(@RequestHeader(value = "Authorization") String token, @PathVariable("id") long id,@RequestBody MaskedLMDTO dto) throws DocumentException {

        Article article=articleService.downloadPDF(id,dto);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/pdf"));
        headers.add("content-disposition", "attachment;filename=" + article.getDateTime() + ".pdf");
        headers.setContentDispositionFormData( article.getDateTime()+ ".pdf", article.getDateTime() + ".pdf");

        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(article.getArticleFile(), headers, HttpStatus.OK);
        return response;
    }
Dilrukshi Perera
  • 917
  • 3
  • 17
  • 31

1 Answers1

1

Can you try calling your server using fetch method and download the PDF using downloadjs available here: https://www.npmjs.com/package/downloadjs?

I guess your code will then look something like:

fetch(endPoints.DOWNLOAD_ARTICLE+"/"+action.payload.article_id, {
  method: 'POST',
  body: obj,
  headers: {
    'Content-Type': 'application/json'
  },
}).then(function(resp) {
  filename = resp.data.filename;
  return resp.blob();
}).then(function(blob) {
  return download(blob, filename);
});
Terry
  • 577
  • 2
  • 5