我正在尝试在角度5上实现从db下载pdf的逻辑。我正面临下载文件中的问题。文件已下载,但在打开时引发错误-“无法加载”。
我看了很多博客和问题/答案,但是找不到我的代码中的错误。
In Database -> pdf file content saved as BLOB
Rest Web服务-> 在下面的代码pdfData中,来自BLOB类型列的数据在这里是Java代码中的byte []。
@GetMapping("downloadReport/{reportId}")
public StreamingResponseBody downloadDocument(byte[] pdfData) {
return outputStream -> {
//This way working for sample
/*try (InputStream inputStream = new ByteArrayInputStream(
Files.readAllBytes(Paths.get("D:/pdfWithoutPassword.pdf")))) {
IOUtils.copy(inputStream, outputStream);
}*/
//This way not working when data fetched from Database
try (InputStream inputStream = new ByteArrayInputStream(pdfData)) {
IOUtils.copy(inputStream, outputStream);
}
outputStream.close();
};
Angular 5代码
downloadReport(reportType: string, reportId: string) {
let fileDownloadUrl = environment.apiUrl + "/downloadReport" + "/" + reportId;
return this.httpClient
.get(fileDownloadUrl, { observe: 'response', responseType: "blob"})
.subscribe(response => this.saveFileToSystem(response.body)),
error => console.log("Error downloading the file."),
() => console.info("OK");
}
saveFileToSystem(input: any) {
const blob = new Blob([input], { type: 'application/octet-stream' });
saveAs(blob, "testingpdf1.pdf");
}
寻求帮助以解决此问题。预先感谢!
答案 0 :(得分:1)
这是我做过的另一种方法,您可以更改:
@RequestMapping(value = "/generateReport", method = RequestMethod.POST)
public ResponseEntity<byte[]> generateReport(){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
StringBuilder filename = new StringBuilder("MyPdfName").append(".pdf");
byte[] bytes = pdfGeneratorService.generatePDF();
headers.add("content-disposition", "inline;filename=" + filename.toString());
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
return response;
}
答案 1 :(得分:0)
尝试一下:
从您的html页面
<a href="javascript:void(0);" (click)="generatePdf()"> YourPdf.pdf </a>
从您的js文件中
generatePdf() {
this.yourService.generatePdf()
.subscribe(pdf => {
let mediaType = 'application/pdf';
let blob = new
Blob([this.converterService.base64ToArrayBuffer(pdf.pdfByteArray)], { type: mediaType });
saveAs(blob, fileName);
}, err => {
console.log('Pdf generated err: ', JSON.stringify(err));
});
}
您的转换器服务:
import { Injectable } from "@angular/core";
@Injectable()
export class ConverterService {
base64ToArrayBuffer(base64) {
var binaryString = window.atob(base64);
var binaryLen = binaryString.length;
var bytes = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++) {
var ascii = binaryString.charCodeAt(i);
bytes[i] = ascii;
}
return bytes;
}
}