Reputation: 404
I have the below requirement, Java server will send the below details by reading the file from server (it can be pdf, doc or image)
Java code:
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];
}
server will return the file as byte array, then this needs to be converted as the original file AngularJS and download
Upvotes: 0
Views: 13266
Reputation:
The following code may be used to create a file on client side based on the response from server:
$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);
}
}
Upvotes: 1
Reputation: 26094
You need to add the response header in server side like below.
response.setHeader("Content-Type", "application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=sample.pdf");
Upvotes: 2