Hi All - I am generating a file in my application and I want to download it without the user having to click on a button.
I have the following code which creates the file to download and adds the Anchor button - but you still have to click the anchor button to actually download the file. Is there anyway of starting the download automatically?
private List<String> bodyList = new LinkedList<String>();
String timeStamp = (new Timestamp(new Date().getTime())).toString();
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(byteArrayOutputStream);
for (String element : bodyList) {
out.writeBytes(element + "\n");
}
InputStream is = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
StreamResource myResource = new StreamResource(csvFileName, () -> is);
Anchor downloadLink = new Anchor(myResource, "Download!");
downloadLink.setId(timeStamp);
downloadLink.getElement().setAttribute("download", true);
hl.add(downloadLink);
} catch (IOException e) {
e.printStackTrace();
}
Hello,
sorry I have the same problem.
I call a function that generates a file xls. After automatically i would download this file without button visible on the UI. How can i do this ?
Thank you
End user starts the process clicking a button. A file xls is generated and my goal is to open this generated file in excel or to download it locally. I would avoid a second click on another button to download or open.
Thank you
Hi,
You need to execute javscript:clickButton on you Anchor component - remember to set an id on the anchor component. You can also set the anchor component to invisible so it does not show on the page. This is the code that works for me:
private void downloadReport(List<String> bodyList, String csvFileName, HorizontalLayout hl) {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(byteArrayOutputStream);
for (String element : bodyList) {
out.writeBytes(element + "\n");
}
InputStream is = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
StreamResource myResource = new StreamResource(csvFileName, () -> is);
Anchor downloadLink = new Anchor(myResource, "Download");
downloadLink.setId(timeStamp);
downloadLink.getElement().getStyle().set("display", "none");
downloadLink.getElement().setAttribute("download", true);
hl.add(downloadLink);
Page page = UI.getCurrent().getPage();
page.executeJavaScript("document.getElementById('"+timeStamp+"').click();");
} catch (IOException e) {
e.printStackTrace();
}
}