2016-02-11 101 views
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); 
}; 

回答

0

的文件中,有一些事情错了,当您尝试发送的字节作为JSON。 这是比较容易直接发送字节:

在服务器上:

公开赛downloadFile的InputStream和复制其内容response.getOutputStream()

在客户端:

var a = document.createElement("a"); 
document.body.appendChild(a); 
a.style = "display: none"; 
var fileName = "test.png"; 

var xhr = new XMLHttpRequest(); 
xhr.open("GET", <theurl>, true); 
xhr.responseType = "blob"; 
xhr.onload = function() { 
    var url = window.URL.createObjectURL(xhr.response); 
    a.href = url; 
    a.download = fileName; 
    a.click(); 
    window.URL.revokeObjectURL(url); 
}; 

xhr.send(); 
+0

谢谢,它完美的作品! – Tone

+0

document.body.appendChild(url); //在FF中需要,对于Chrome可选 否则它不会在FF上工作 –

相关问题