【发布时间】:2016-02-11 18:58:35
【问题描述】:
在 javasript 中,我有一个字节数组,想将其转换回原始文件类型并打开它。我已经尝试过使用 image/png 和 application/pdf 但结果是一样的。文件已损坏,无法打开。有关如何执行此操作的任何建议?
服务器端,我的java代码是这样的:
...
File downloadFile = myService.retriveMyFile(input);
byte[] fileInBytes = new byte[(int)downloadFile.length()];
InputStream inputStream = null;
try {
inputStream = new FileInputStream(downloadFile);
inputStream.read(fileInBytes);
} finally {
inputStream.close();
}
String json = new Gson().toJson(fileInBytes);
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
在javascript中我尝试像这样打开文件
...
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var fileName = "test.png";
xhr.onload = function () {
if (xhr.status === 200) {
var jsonResponse = xhr.response;
var json = JSON.stringify(jsonResponse),
blob = new Blob([json], {type: "image/png"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
【问题讨论】:
标签: javascript java json