2016-07-08 59 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");