我正在使用 Angular8 和 Spring Boot 下载文件。我想打开我在新选项卡中保存的 PDF 文件,您可以帮助我而不是下载它们吗?
FileDownload(fileId: number, headers): Observable<any> {
return this.http.get(apiHost + '/downloadFile/' + fileId, { headers, responseType: 'blob' as 'json' });
}
downloadFile(event): void {
const headers = new HttpHeaders();
this.service.FileDownload(event.fileId, headers).subscribe(response => {
let dataType = response.type;
let binaryData = [];
binaryData.push(response);
let downloadLink = document.createElement('a');
downloadLink.href = window.URL.createObjectURL(new Blob(binaryData, { type: dataType }));
if (event.fileName)
downloadLink.setAttribute('download', event.fileName);
document.body.appendChild(downloadLink);
downloadLink.click();
})
}
更新(工作代码)
this.service.FileDownload(event.fileId, headers).subscribe(response => {
let dataType = response.type;
let binaryData = [];
binaryData.push(response);
const fileURL = URL.createObjectURL(new Blob(binaryData, { type: dataType }));
window.open(fileURL, '_blank');
})
Spring Booot (inline)
response.setHeader("Content-Disposition", String.format("inline; filename=\"%s\"", fileName));
window.open(downloadLink.href, '_blank')
这是我的控制器方法:
@GetMapping("file/**")
public ResponseEntity<InputStreamResource> get(HttpServletRequest request) throws FileNotFoundException {
final String pathFromUrl = ((String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).replaceFirst("/file/", "");
final String decoded = URLDecoder.decode(pathFromUrl, StandardCharsets.UTF_8);
HttpHeaders headers = new HttpHeaders();
Path filePath = filesFolder.resolve(decoded);// filesFolder - path to the root folder of your files
final String fileName = filePath.getFileName().toString();
// 'Content-Disposition' should be 'inline'
headers.add("Content-Disposition", "inline; filename=\"" + fileName + "\"");
final InputStream is = new FileInputStream(filePath.toFile());
final BodyBuilder bodyBuilder = ResponseEntity.ok().headers(headers);
final String extension = FilenameUtils.getExtension(fileName);
final BodyBuilder contentType;
logger.error(extension);
switch(extension) {
case "pdf":
// and 'Content-Type' should be 'application/pdf'
// you can use header('Content-Type: application/pdf');
// or bodyBuilder.contentType(MediaType.APPLICATION_PDF);
contentType = bodyBuilder.contentType(MediaType.APPLICATION_PDF);
break;
default:
contentType = bodyBuilder.contentType(MediaType.APPLICATION_OCTET_STREAM);
}
return contentType.body(new InputStreamResource(is));
}
和 HTML:
<a th:href="/file/pdffile.pdf" target="_blank">