从服务器下载字节数组作为AngularJS中的原始文件

时间:2016-07-08 07:11:01

标签: java angularjs

我有以下要求, Java服务器将通过从服务器读取文件(可以是pdf,doc或image)来发送以下详细信息

Java代码:

public static byte[] downloadFileAsStream(String fileName) throws IOException, MalformedURLException 
File file = new File(fileName);
if (!file.exists()) {
  // File not found
  return null;
}

try {
  InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
  return readFileAsByte(file.getAbsolutePath());
} catch (FileNotFoundException ex) {
  ex.printStackTrace();
}
return null;
}

private static byte[] readFileAsByte(String filePath) {

try {
  Path path = Paths.get(filePath);
  return Files.readAllBytes(path);
} catch (IOException ex) {
  ex.printStackTrace();
}
return new byte[0];
}

服务器将文件作为字节数组返回,然后需要将其转换为原始文件AngularJS并下载

2 个答案:

答案 0 :(得分:2)

您需要在服务器端添加响应标头,如下所示。

 response.setHeader("Content-Type", "application/pdf");
 response.setHeader("Content-Disposition", "attachment; filename=sample.pdf");

答案 1 :(得分:1)

以下代码可用于根据服务器的响应在客户端创建文件:

$http.post("<SERVER_URL>", "<PARAMS_IF_ANY>", {
    responseType:'arraybuffer'
}).success(function(data, status, headers) {
    var contentType = headers["content-type"] || "application/octet-stream";
    var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
    if (urlCreator) {
        var blob = new Blob([data], { type: contentType });
        var url = urlCreator.createObjectURL(blob);
        var a = document.createElement("a");
        document.body.appendChild(a);
        a.style = "display: none";
        a.href = url;
        a.download = "download.pdf"; //you may assign this value from header as well 
        a.click();
        window.URL.revokeObjectURL(url);
    }
}