无法通过 Servlet 下载从 BLOB 检索到的 PDF



我环顾四周,尝试了一些我看到的解决方案,但似乎没有任何效果。

所以这是我的情况:

我有一个PDF文件作为BLOB存储在我的oracle数据库中。 在我的后端,我调用我的服务以下载该pdf(在我的实体中,pdf是一个byte[](,如下所示:

@GET
@Path("/downloadpdf")
@Produces("application/pdf")
public HttpServletResponse downloadPdf(@Context HttpServletRequest request, @Context HttpServletResponse response) {
try {
UserGuideJpaService userGuideService = new UserGuideJpaServiceImpl();
HashMap<String, Object> result = userGuideService.getPdfGuide();
if ("0".equals(result.get("returnCode"))) {
UserGuide userGuide = (userGuide) result.get("userGuide");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-control", "private");
response.setDateHeader("Expires", 0);
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename="APP - User Guide.pdf"");
byte[] pdf = userGuide.getPdf();
if (pdf != null) {
response.setContentLength(pdf.length);
ServletOutputStream out = response.getOutputStream();
out.write(pdf);
out.flush();
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}

回到我的前端,我有这个:

注意:这是我的response.data的样子(它是一个字符串(:

%

PDF-1.4 %

8 0 obj <</type/page/resources <</procSet [/PDF/text ]/font 4 0 R/阴影 6 0 R/ExtGState 7 0 R

/媒体框 [0 0 595.28 864.00]/内容 9 0 R/父 10 0 R>> endobj

9 0 obj <</长度 1679/过滤器 [/Flate解码 ]>>流 x x n7 ?84 aw =I Jr v %ڝ@ Q a s + r %E_- % {x | 1 o Oo { ،j bCN_3 81 { ̭] 9 rXU e T]WV m q5|\5 a ꞽ" T0n~" O X 9#~+ b 5 7 9 ( R/f 5xF 5 WW eA lr}A." 7Ej iƳ] \ ^ +f צ UT <1 , ZrE3 s 4 bzU,f 4 ̎ U *7 ̋ vN΋ 4 ' 䌜 ^ Nf#! ~2 \G+ _ , b<2/WIU V 2% B {Z d H ̀R . g%@ 0Ln( 9...

和JavaScript方面:

$scope.downloadPdf = function() {
APIClientService.downloadPdf().then(function(response) {
// #1
var URL, blob, downloadLink, downloadUrl;
downloadLink = document.createElement('a');
downloadLink.target = '_blank';
downloadLink.download = 'APP - User Guide.pdf';
blob = new Blob([response.data], {
type: 'application/pdf'
});
URL = window.URL || window.webkitURL;
downloadUrl = URL.createObjectURL(blob);
downloadLink.href = downloadUrl;
document.body.append(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
URL.revokeObjectURL(downloadUrl);
// # 2
window.open("data:application/pdf," + encodeURI(response.data));
// # 3
window.open("data:application/pdf," + escape(response.data));
});
};

但是,这不会下载文件,甚至不会打开它。

而且我很确定 pdf 在后端是正确的,因为我在使用时设法获得了它:

OutputStream out = new FileOutputStream("Test.pdf");
out.write(pdf);
out.close();

然后如何从我的浏览器下载pdf?或者至少打开它?

编辑:这是来自APIClientService的方法:

({
downloadPdf: function() {
return $http({
method: 'GET',
url: this.baseUrl + "/downloadpdf"
});
}
});

默认情况下,ajax 请求将你的响应视为文本,这将导致非文本文件出现问题。

为了防止这种情况,请在请求中添加二进制响应类型,如下所示

({
downloadPdf: function() {
return $http({
method: 'GET',
url: this.baseUrl + "/downloadpdf",
responseType: "blob"
});
}
});

最新更新