Download vaadin file

I made a taable with its data source set to BeanItemContainer. Each bean has a name (String) and a byte [], which contains a file converted to byte []. I added a button for each line, which is supposed to load the file, first converting it to pdf. I am having problems implementing the downloadable part, here is the code related:

public Object generateCell(Table source, Object itemId, Object columnId) { // TODO Auto-generated method stub final Beans p = (Beans) itemId; Button l = new Button("Link to pdf"); l.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { // TODO Auto-generated method stub try { FileOutputStream out = new FileOutputStream(p.getName() + ".pdf"); out.write(p.getFile()); out.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); l.setStyleName(Reindeer.BUTTON_LINK); return l; } }); 

So getFile gets byte array from bean

+4
source share
2 answers

If you are using Vaadin 7, you can use the FileDownloader extension as described here: https://vaadin.com/forum#!/thread/2864064

Instead of using a clicklistener, you will just need to click a button:

 Button l = new Button("Link to pdf"); StreamResource sr = getPDFStream(); FileDownloader fileDownloader = new FileDownloader(sr); fileDownloader.extend(l); 

To get a StreamResource:

 private StreamResource getPDFStream() { StreamResource.StreamSource source = new StreamResource.StreamSource() { public InputStream getStream() { // return your file/bytearray as an InputStream return input; } }; StreamResource resource = new StreamResource ( source, getFileName()); return resource; } 
+8
source

Creating the created columns is well described in the Vaadin book , one amendment to your code would be to check the columnId or propertyId to ensure the creation in the right column - it currently seems like you are returning a button for any column.

Something like that:

 public Object generateCell(CustomTable source, Object itemId, Object columnId) { if ("Link".equals(columnId)) { // ...all other button init code is omitted... return new Button("Download"); } return null; } 

To upload a file:

 // Get instance of the Application bound to this thread final YourApplication app = getCurrentApplication(); // Generate file basing on your algorithm final File pdfFile = generateFile(bytes); // Create a resource final FileResource res = new FileResource(pdfFile, app); // Open a resource, you can also specify target explicitly - // ie _blank, _top, etc... Below code will just try to open // in same window which will just force browser to show download // dialog to user app.getMainWindow().open(res); 

More information on how to handle resources can be found in the book of Vaadin .

+3
source

Source: https://habr.com/ru/post/1489159/


All Articles