4.7.9.2. Downloading Files

Files can be downloaded from the file storage to the user’s computer by using the ExportDisplay interface. It can be obtained by calling the AppConfig.createExportDisplay() static method or via injection in the controller class. For example:

AppConfig.createExportDisplay(this).show(fileDescriptor);

The show() method accepts an optional ExportFormat type parameter, which defines the type of the content and the file extension. If the format has not been provided, the extension is retrieved from the FileDescriptor, and the content type is set to application/octet-stream.

The file extension defines whether the file is downloaded via the browser’s standard open/save dialog (Content-Disposition = attachment), or if the browser will attempt to show the file in the browser window (Content-Disposition = inline). The list of extensions for files that should be shown in the browser window is defined by the cuba.web.viewFileExtensions application property.

ExportDisplay also enables downloading of arbitrary data if ByteArrayDataProvider is used as a parameter of the show() method. For example:

public class SampleScreen extends AbstractWindow {

    @Inject
    private ExportDisplay exportDisplay;

    public void onDownloadBtnClick(Component source) {
        String html = "<html><head title='Test'></head><body><h1>Test</h1></body></html>";
        byte[] bytes;
        try {
            bytes = html.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        exportDisplay.show(new ByteArrayDataProvider(bytes), "test.html", ExportFormat.HTML);
    }
}