How to *change* FileDownloader for a Button?

I have a dialog in which the user chooses the format of the file to be downloaded (CSV, PDF) from a combo box and then hits the OK button to begin the download. I currently have a method that gets called from the combo box’s ValueChangeListener that looks something like this:

		ExportedReportDataSource dataSource = new ExportedReportDataSource(response);
		StreamResource resource = new StreamResource(dataSource, filename);
		resource.setMIMEType("application/" + exportFormat.getValue());
		resource.getStream().setParameter("Content-Disposition", "attachment; filename="+filename);
		FileDownloader downloader = new FileDownloader(resource);
		downloader.extend(okButton);

The problem is that as I select different formats, more and more downloaders get called whenever the OK button is selected! I need a way to “unextend” the previous downloader’s association with the OK button.

I hope my problem statement is clear enough. Any info is much appreciated.

I think AbstractExtension.remove() or ClientConnector.removeExtension(Extension) should do the trick.

Why do you create new and new FileDownloader every time, the combo value changed? Use just com.vaadin.server.FileDownloader.setFileDownloadResource(Resource) method in your listener.

…or you do something like this: new FileStream(getStream()).extend(button); ... public StreamResource getStream(){ StreamResource sr; //Create your StremResource dynamically. return sr; }

Outside value change listener:

final FileDownloader downloader = new FileDownloader(a_dummy_resource); downloader.extend(okButton); Inside value change listener:

ExportedReportDataSource dataSource = new ExportedReportDataSource(response);
StreamResource resource = new StreamResource(dataSource, filename);
resource.setMIMEType("application/" + exportFormat.getValue());
resource.getStream().setParameter("Content-Disposition", "attachment; filename="+filename);
downloader.setFileDownloadResource(dataSource);

Thanks everyone! I ended up using the setFileDownloadResource() method. Everything works now.

Hello!

I’m here to tell that the below code, using button ClickListener event and setFileDownloadResource from FileDownloader worked fine for me:

final FileDownloader fileDownloader = new FileDownloader(resource);
fileDownloader.setOverrideContentType(false);
downloadButton.addClickListener(listener -> {
	StreamSource newSource = getStreamSource(simulationStockComboBoxFilter, defaultValue); //my custom StreamSource getter
	StreamResource newResource = new StreamResource(newSource,
			fileNameBeginning + formatter.format(LocalDateTime.now()) + ".xls");
	newResource.setMIMEType("application/vnd.ms-excel");
	fileDownloader.setFileDownloadResource(newResource);
});
fileDownloader.extend(downloadButton);

IMPORTANT: One thing that is mandatory for this to work is to use different filenames for every downloaded file, so that we don’t use the browser cache.