我试图通过从Angular 6和Spring框架中打开PDF文档来实现示例。我尝试过:
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;
}
服务:
@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({
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');
});
}
}
我可以在新标签页中下载文件,但必须单击“启用”弹出窗口。有没有无需手动单击启用弹出窗口即可实现此目的的方法?也许我需要更改返回对象的类型?