【问题标题】:javascript: open file from byte array returned by jsonjavascript:从 json 返回的字节数组打开文件
【发布时间】: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


    【解决方案1】:

    当您尝试以 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();
    

    【讨论】:

    • document.body.appendChild(url); //在FF中是必需的,对于Chrome是可选的,否则它不会在FF上工作
    猜你喜欢
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多