2016-07-08 11 views
0

からAngularJSで、元のファイルとバイト配列をダウンロードし、 Javaサーバーは、サーバーからファイルを読み込むことで、以下の内容を送信しますコード:Javaの</p> <p>(それはPDF、DOCまたはイメージすることができます)私は、以下の要件を持っているサーバー

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"); 
関連する問題