2016-02-11 46 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上工作 –

相關問題