2
在javasript中,我有一个字节数组,并希望将其转换回原始fileType并将其打开。我已经尝试使用image/png和application/pdf,但结果是一样的。该文件已损坏,无法打开。有关如何做到这一点的任何建议?javascript:从json返回的字节数组打开文件
服务器端,我的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);
};
谢谢,它完美的作品! – Tone
document.body.appendChild(url); //在FF中需要,对于Chrome可选 否则它不会在FF上工作 –