How to achieve "click-button-to-download-file" in vaadin 7

Hi Nikolay I tried SimpleFileDownload with a simple test code, but when I click on button nothing happens.

        final SimpleFileDownloader downloader = new SimpleFileDownloader();
        addExtension(downloader);
        
        Button button = new Button("Click Me");
        button.addClickListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                final StreamResource resource = new StreamResource(new StreamSource() {
                    @Override
                    public InputStream getStream() {
                        return new ByteArrayInputStream("This is test clicked on button".getBytes());
                    }
                }, "testButton.txt");
                
                downloader.setFileDownloadResource(resource);
                downloader.download();
            }
        });
        myLayout.addComponent(button);

Hi Piero!

Could you please provide more information about your test?
And what browser are you using for testing?
Thank you!

Mac OSX 10.10.5
Java 1.8.0_112-b16
Eclipse Neon.2 release 4.6.2
Apache Tomcat 8.0.39
Vaadin plugin 3.0.0
Browsers used: Firefox 50.1.0 and Safari 10.0.2

And are you adding extension to UI or some component? Vaadin version is 7?

Vaadin 7.7.6
I’m not adding extension. I’m testing this code in a window of my application.

ok, could you please provide source code of this window?

I’ve resolved. The problem was Ivy, after ivy caches clean now works.
But I’ve another question: using Page.getCurrent().open(resource, filename, true) the browser let the user to select action: save or open (the file is a pdf), but with SimpleFileDownloader there is only save option.
Can I use SimpleFileDownloader in that way?

Unfortunatully you can’t. But I will try to add such feature in the future :slight_smile:

Ok thanks! :slight_smile:

Hi,

I am supper newbe to this framework and been given a task to work on few tasks out of which downlaoding the table content by selecting a variouse format via Combobox like xls, csv, geojson which is json text file, .dat file. I tried to use CSVExporter(tablecontent); and get the object to dawnload. but I wasnt able to ;(. any idea or similar work would be greatly appreciated. here is my code snippit,

private CSVExporter exporter;

ComboBox exportcombo = new ComboBox();

exportcombo.addItems(“Export”,“AWIPS II”,“CSV”,“Email Addresses”,“ESRI Shapefile”,“GeoJSON”,
“Gibson Rigde Placefile”,“KML”,“Mailing Lables”);

    exportcombo.addValueChangeListener(new ValueChangeListener() {

        public void valueChange(ValueChangeEvent event) {
            exportType = (String) exportcombo.getValue();
            exportcombo.setValue("Export");
            if (exportType.equals("CSV")) {
                exporter = new CSVExporter(contactTable);
                exporter.getData();
            } else if(exportType.equals("GeoJSON")){
            //
            }

        }

it’s passable to generate a new file and download it when button click event happend

here
1)if i add click Listener it generate a file but not able to download it
2) if i extend that button it not generate a file

i try this but it not download a file

public class TestvaadinUI extends UI {

@WebServlet(value = "/*", asyncSupported = true)
@VaadinServletConfiguration(productionMode = false, ui = TestvaadinUI.class)
public static class Servlet extends VaadinServlet {
}

@Override
protected void init(VaadinRequest request) {
    
    final VerticalLayout layout = new VerticalLayout();
    layout.setMargin(true);
    setContent(layout);

    SimpleFileDownloader downloader = new SimpleFileDownloader();
    addExtension(downloader);
    
    
    StreamResource resource=getPDFStream(new File("/home/likewise-open/KONNECTBI/kirubakaran.m/Downloads/ARGEN-711.doc"));
    
    downloader.setFileDownloadResource(resource);
    
    Button button = new Button("Click Me");
    button.addClickListener(new Button.ClickListener()
    {
        public void buttonClick(ClickEvent event) 
        {
            
            downloader.download();
        }
    });
    layout.addComponent(button);
    
}


private StreamResource getPDFStream(File inputfile) {
    
    StreamResource.StreamSource source = new StreamResource.StreamSource() {

        public InputStream getStream() {
           
            InputStream input=null;
            try
            {
                input = new  FileInputStream(inputfile);
            } 
            catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }
              return input;

        }
    };
  StreamResource resource = new StreamResource ( source, inputfile.getName());
    return resource;

}

}

I tested your example on version 2.0.2 and it works fine. Probably something wrong with file (permissions or it’s not exist at the moment when you trying to download it).

that is greate can you please send me a example program

am using simple file downloader 2.0.2

here is it need to complie it’s widget?

am trying the below code to download my on fly excel file but nothing happen when click on button

plz check the code and correct me if anything wrong

   SimpleFileDownloader downloader = new SimpleFileDownloader();
    addExtension(downloader);
         
    Button button = new Button("Click Me");
    button.addClickListener(new Button.ClickListener()
    {
        public void buttonClick(ClickEvent event) 
        {
            StreamResource resource=getStream(new File("/home/likewise-open/KONNECTBI/kirubakaran.m/Downloads/DL_TSTMDLLD.xlsx"));
            downloader.setFileDownloadResource(resource);
            downloader.download();
        }
    });
    
    gl.addComponent(button, 4, 0);
    
}


private StreamResource getStream(File inputfile) {
    
    StreamResource.StreamSource source = new StreamResource.StreamSource() {

        public InputStream getStream() {
           
            InputStream input=null;
            try
            {
                input = new  FileInputStream(inputfile);
            } 
            catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }
              return input;

        }
    };
  StreamResource resource = new StreamResource ( source, inputfile.getName());
    return resource;

}

Sure, here is repository.
https://github.com/tdq/AddonTest

.hi. i am trying to set file name dynamically in a FileDownloader. i’v done this:[code]
StreamResource myResource = createResource();
FileDownloader downloader = new FileDownloader(myResource)
{
@Override
public boolean handleConnectorRequest(VaadinRequest request , VaadinResponse response , String path)
throws IOException{
myResource.setFileName(“new.txt”);
return super
.handleConnectorRequest(request,response,path);

    }

};
Button dounloadButton = new Button(“Download Button”);
downloader.extend(downloadButton);

private StreamResource createResource(){
return new StreamResource(new StreamSource()
{
@Override
public InputStream getStream(){
File file = new File(“test.txt”);
try{

                   }catch(FileNotFoundException ex){
                          Logger.getLogger(FormSearch.class.getName()).log(Level.SEVERE,null,ex);
                   }
                   return null;
            }
},"test.txt");

}
[/code]

But the handleConnectorRequest method was not called.I do not how this method works and what should i do to call that? I’m new to everything! so if my question is obscure, let me know(give me comment).

I’ve tried to setup SimpleFileDownloader but nothing happens for me too. That being said I had to remove the line

addExtention(

Your method addExtension is linked to what Object? I ask because I have a static method that handles the mouse click and so it won’t compile because addExtension has to be linked to some kind of class…

It’s not on the Layout, the Button, etc., so what object addExtension in? That’s the only line I can’t seem to add anywhere…

Please do not call it from a click listner method. Create the FileDownloader object when you create the button itself and extend the filedownloder object with button created. Next time when u click the buttion everything will work fine. Hope this helps. I struggled alot with this finally found this solution

[code]
Button runReportBtn = new Button(PageConst.RUN_REPORT_CAPTION);
FileDownloader downloader = new FileDownloader(new StreamResource(
                new StreamResource.StreamSource() { 
                    private static final long serialVersionUID = 423966284085861068L;
                    @Override 
                    public InputStream getStream() { 
                     // Your method which will provide the input stream.
                    } 
                },"PDF_"+System.currentTimeMillis()+".pdf")); 
downloader.extend(runReportBtn);
        hLayout.addComponent(runReportBtn);
[/code]

Hi Stephan!

In current example it’s linked to MainUI class which extends UI class.

Hi,

This sample is excel download sample.
buttonClick()…

SimpleDateFormat sdf = new SimpleDateFormat("dd_MM_HH_mm_ss");
File file = generateReportFile();
if (file != null) {
sendConvertedFileToUser(file, branchName + "_" + sdf.format(new Date()) + ".xlsx");
}
private File generateReportFile() {
File tempFile = null;
FileOutputStream fileOut = null;
try {
  tempFile = File.createTempFile("tmp", ".xlsx");
  fileOut = new FileOutputStream(tempFile);
  workbook.write(fileOut);
} catch (final IOException e) {
  return null;
} finally {
  if (tempFile != null) {
     tempFile.deleteOnExit();
  } try {
    if (fileOut != null) {
       fileOut.close();
    }
  } catch (final IOException e) {
    e.printStackTrace();
  }
}
return tempFile;
}

private boolean sendConvertedFileToUser(final File fileToExport, final String exportFileName) {
  UI ui = UI.getCurrent();
  TemporaryFileDownloadResource resource;
  try {
     resource = new TemporaryFileDownloadResource(ui, exportFileName, this.EXCEL_MIME_TYPE, fileToExport);
     ui.getPage().open(resource, null, false);
  } catch (final FileNotFoundException e) {
    return false;
  } return true;
}