2016-07-08 55 views
0

在AngularJS一个原始文件我有以下要求, Java服务器将通过读取服务器上的文件发送以下信息(也可以是PDF,DOC或图像)下载字节数组作为从服务器

的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和下载

回答

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); 
    } 
} 
2

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

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