I am working to download a pdf file from User Interface (Angular), generated from Spring boot . I am able to download pdf file from browser with same API.
Quick help will be much appreciated.
In postman it gives response like this -
When trying from UI then getting below error-
SyntaxError: Unexpected token % in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad message: "Unexpected token % in JSON at position 0" stack: "SyntaxError: Unexpected token % in JSON at position 0↵ at JSON.parse ()↵ at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:19662:51)↵
API Code
Controller code-
@RequestMapping(value = "/downloadPDF/", method = RequestMethod.GET, produces = "application/pdf")
public ResponseEntity<Resource> downloadServicePack(@RequestHeader("Authorization") String token,
HttpServletRequest request) throws WorkflowException, Exception {
String fileName = "TWEVL_ServiceDesignPack.pdf";
// String fileName ="ServiceDesignPdf.pdf";
Resource resource = fileStorageService.loadFileAsResource(fileName);
// Try to determine file's content type
String contentType = null;
try {
contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
} catch (IOException ex) {
// logger.info("Could not determine file type.");
}
// Fallback to the default content type if type could not be determined
if (contentType == null) {
contentType = "application/octet-stream";
}
return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
Service Code-
@Service
public class FileStorageService {
private final Path fileStorageLocation;
@Autowired
public FileStorageService(FileStorageProperties fileStorageProperties) throws Exception {
this.fileStorageLocation = Paths.get(fileStorageProperties.getUploadDir())
.toAbsolutePath().normalize();
try {
Files.createDirectories(this.fileStorageLocation);
} catch (Exception ex) {
throw new Exception("Could not create the directory where the uploaded files will be stored.", ex);
}
}
public Resource loadFileAsResource(String fileName) throws Exception {
try {
Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
Resource resource = new UrlResource(filePath.toUri());
if(resource.exists()) {
return resource;
} else {
throw new Exception("File not found " + fileName);
}
} catch (Exception ex) {
throw new Exception("File not found " + fileName, ex);
}
}
}
Angular Code-
JWT Interceptor to pass token & other header-
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
// add authorization header with jwt token if available
const token = this.authenticationService.currentUserValue;
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token.token}`,
Accept: `application/pdf`,
responseType:'blob',
'Content-Type':`application/pdf`
}
});
return next.handle(request);
}
}
API Call
downloadServicePackPDF() {
this.tcmtSrv
.downloadServicePack()
.subscribe(
(blob: Blob) => {
console.log('report is downloaded');
},
(error) => {
console.log(error);
}
);
}
Service Code -
downloadServicePack() {
//header is being passed from interceptor
return this.apiSrv.get(DOWNLOAD_SERVICE_PACK,'');
}