我有一个运行码头的Java服务器,该码头将发送base64编码的excel文件作为对客户端请求的响应。 在客户端上收到响应后,我可以访问/解码响应,但是,下载导致文件无法由excel打开。
在文本编辑器中打开生成的客户端文件看起来就像一个有效的excel文件(16进制束)。我还有什么遗漏?
Java代码(使用spark):
get("/file", (request, response) -> {
File file = new File(".\\file.xlsx");
InputStream is = new FileInputStream(file);
byte[] buff = new byte[(int)file.length()];
int bytesRead = 0;
ByteArrayOutputStream bao = new ByteArrayOutputStream();
while((bytesRead = is.read(buff)) != -1){
bao.write(buff, 0, bytesRead);
}
is.close();
byte[data] = bao.toByteArray();
response.header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//creates an encoded string as intended
response.body(new String(Base64.encodeBase64(data)));
return response.body();
});
JavaScript代码(原始):
function download(window) {
let text;
let blob;
let reader = new FileReader();
reader.onloadend = function(e) {
//decodes base64 encoded response (file) from server
text = window.atob(e.srcElement.result);
blob = new Blob([text], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})
let url = window.URL.createObjectURL(blob);
let downloadLink = document.createElement('a');
downloadLink.href = url;
downloadLink.download = "excelFile.xlsx";
downloadLink.click();
downloadLink.remove();
}
fetch("http://javaServer.com/file")
.then(response => response.blob())
.then(blob => {
this.blob = blob;
//triggers 'onloadend' event handler
reader.readAsText(blob);
});
}
download(window);