【发布时间】:2019-04-12 11:33:48
【问题描述】:
使用 Angular 6 在新选项卡中打开 PDF 文件。我试过这个:
休息控制器:
@RestController
@RequestMapping("/downloads")
public class DownloadsController {
private static final String EXTERNAL_FILE_PATH = "/Users/test/Documents/blacklist_api.pdf";
@GetMapping("export")
public ResponseEntity<InputStreamResource> export() throws IOException {
ClassPathResource pdfFile = new ClassPathResource(EXTERNAL_FILE_PATH);
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity.ok().headers(headers).contentLength(pdfFile.contentLength())
.contentType(MediaType.parseMediaType("application/pdf"))
.body(new InputStreamResource(pdfFile.getInputStream()));
}
}
服务:
@Injectable({
providedIn: 'root'
})
export class DownloadService {
constructor(private http: HttpClient) {
}
exportPdf() {
return this.http.get(environment.api.urls.downloads.getPdf, { responseType: 'blob' });
}
}
组件:
@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() {
window.open(this.downloadService.exportPdf());
}
}
HTML 代码:
<h1 class="title">Export</h1>
<div class="content grid-wrapper">
<div class="export">
<button class="btn btn-secondary" (click)="export()">Export</button>
</div>
</div>
当我单击按钮时,为了在新选项卡中打开 PDF 文档,实现 Angular 服务和组件的正确方法是什么?
你能建议吗?
【问题讨论】:
-
您不能只使用来自后端的响应。您必须创建 Blob 对象,然后创建链接并自动打开它或用于
<embed>。有关详细信息,请参阅stackoverflow.com/questions/21628378/…。 @edit:线程用于 Angular.JS,但您需要的部分是用 vanilla js 编写的 -
我用我尝试实现的实现更新了答案,但仍然出现错误。你能建议如何解决它吗?
-
你能发布你从服务器得到的响应吗?
-
使用上面的代码,我得到了具有相同页面的新标签:PDF 文档未显示。
标签: angular typescript angular6