I am trying to open a pdf file in the next tab, it opens but is always blank. I am calling a pdf file from a folder in my springboot. The data does show in the console log .
Spring code:
@RequestMapping(value = "/report", method = RequestMethod.GET)
void getFile(HttpServletResponse response) throws IOException {
String fileName = "test123.pdf";
String path = "TrainingDocuments/SuperPartnerUser/" fileName;
File file = new File(path);
FileInputStream inputStream = new FileInputStream(file);
response.setContentType("application/pdf");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "inline;filename=\"" fileName "\"");
FileCopyUtils.copy(inputStream, response.getOutputStream());
}
React code:
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:application/pdf;charset=utf-8,' encodeURIComponent(text));
element.setAttribute('target','_blank');
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
function test () {
Api(`tempFileDownload/report`, 'Get',"",3).then((data) => {
console.log(data);
download("test",data)
const file = new Blob([ data ], { type: 'application/pdf' });
//Build a URL from the file
const fileURL = URL.createObjectURL(file);
//Open the URL on new Window
window.open(fileURL);
});
}
CodePudding user response:
Issue was the api call for the frontend, backend works fine; Reponse type needed to be blob
const result = await axios({
url: `${localUrl url}`, //your url
method: 'GET',
responseType: 'blob', // important
})
.then(({ data }) => data);
return result;