I'm trying to implement example with opening PDF document from Angular 6 and Spring framework. I tried this:
private static final String EXTERNAL_FILE_PATH = "/Users/test/Documents/blacklist_api.pdf";
@GetMapping(path="export")
public ResponseEntity<byte[]> export() throws IOException {
File pdfFile = Paths.get(EXTERNAL_FILE_PATH).toFile();
byte[] fileContent = Files.readAllBytes(pdfFile.toPath());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
// Here you have to set the actual filename of your pdf
headers.setContentDispositionFormData(pdfFile.getName(), pdfFile.getName());
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0, no-cache, no-store, must-revalidate");
headers.setPragma("no-cache");
ResponseEntity<byte[]> response = new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
return response;
}
Service:
@Injectable({
providedIn: 'root'
})
export class DownloadService {
constructor(private http: HttpClient) {
}
downloadPDF(): any {
return this.http.get(environment.api.urls.downloads.getPdf, {
responseType: 'blob'
})
.pipe(
map((res: any) => {
return res
})
);
}
}
Component:
@Component({
selector: 'app-download',
templateUrl: './download.component.html',
styleUrls: ['./download.component.scss']
})
export class DownloadComponent implements OnInit {
constructor(private downloadService: DownloadService,
private router: Router,
private route: ActivatedRoute) {
}
ngOnInit() {
}
export() {
this.downloadService.downloadPDF().subscribe(res => {
const fileURL = URL.createObjectURL(res);
window.open(fileURL, '_blank');
});
}
}
I can download the file in new tab but I have to click enable popup. Is there are way to implement this without manually clicking on enable popup? Probably I need to change the type of the returned object?