I have a Java web application that serves a file:
@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();
}
}
I am extracting the file in the client, and base64 encodes it with 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);
}
The problem is that the value stored in local storage is incorrect. The encoded data is different from the one I get when I download a PDF using this snapshot . I do not know if the problem is how I serve the file or the encoding process in the client.
Value stored looks like this
data:application/pdf;base64,JVBERi0xLjQKJe+/ve+/ve+/ve+/vQoxIDAgb...
instead
data:application/pdf;base64,JVBERi0xLjQKJeHp69MKMSAwIG9iago8PC9Ue...
source
share