@RequestMapping(value = "/pdf/download", method = RequestMethod.GET)
public void download(
HttpServletRequest request,
HttpServletResponse response,
@RequestParam(value = "id", required = true) Long id) throws IOException {
File pdfFile = pdfFileManager.getFromId(id);
response.setContentType("application/pdf");
response.addheader("Content-disposition", "attachment; filename=download");
response.setContentLength((int) pdfFile.length());
FileInputStream fileInputStream = null;
OutputStream responSEOutputStream = null;
try {
fileInputStream = new FileInputStream(pdfFile);
responSEOutputStream = response.getoutputStream();
int bytes;
while ((bytes = fileInputStream.read()) != -1) {
responSEOutputStream.write(bytes);
}
responSEOutputStream.flush();
} finally {
fileInputStream.close();
responSEOutputStream.close();
}
}
我在客户端检索文件,base64使用FileReader对其进行编码:
$.ajax({
url: "/pdf/download?id=" + id,
dataType: "application/pdf",
processData: false
}).always(function(response) {
if(response.status && response.status === 200) {
savePdf(response.responseText, "download_" + id);
}
});
function savePdf(pdf, key) {
var blob = new Blob([pdf], {type: "application/pdf"});
var fileReader = new FileReader();
fileReader.onload = function (evt) {
var result = evt.target.result;
try {
localStorage.setItem(key, result);
} catch (e) {
console.log("Storage Failed: " + e);
}
};
fileReader.readAsDataURL(blob);
}
问题是本地存储中保存的值不正确.编码数据与我使用this snip上传PDF时得到的数据不同.我不知道问题是我如何在客户端中提供文件或编码过程.
存储的值是这样的
data:application/pdf;base64,JVBERi0xLjQKJe+/ve+/ve+/ve+/vQoxIDAgb...
代替
data:application/pdf;base64,JVBERi0xLjQKJeHp69MKMSAwIG9iago8PC9Ue...
解决方法:
解决了将请求的响应类型设置为blob的问题:
var xhr = new XMLHttpRequest();
xhr.open("GET", "/pdf/download?id=" + id);
xhr.responseType = "blob";
xhr.onload = function() {
if(xhr.status && xhr.status === 200) {
savePdf(xhr.response, "download_" + id);
}
}
xhr.send();
function savePdf(pdf, key) {
var fileReader = new FileReader();
fileReader.onload = function (evt) {
var result = evt.target.result;
try {
localStorage.setItem(key, result);
} catch (e) {
console.log("Storage Failed: " + e);
}
};
fileReader.readAsDataURL(pdf);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。