Downloading and Displaying Files

This section explains how to download files to the user’s computer or display files in UI. For information on how to get files from the server through REST API, see the Files API section.

Using Downloader

The Downloader bean is designed to download files to the user’s computer. It has a number of download() methods that accept different parameters defining downloaded content.

The file can be either downloaded or shown by the browser in a new tab. It depends on the file type and the value of the jmix.ui.view-file-extensions property. The file type is determined by the DownloadFormat parameter, or, if it is not provided, by the file name extension. You can also force showing the content instead of downloading it regardless of the type by invoking the setShowNewWindow(true) method of Downloader.

Downloading from File Storage

The download() method with the FileRef value allows you to download file from the file storage. The FileRef object contains all necessary information about the file, so you can just pass it alone to Downloader:

@Autowired
private Downloader downloader;

private void downloadFromFileStorage(Attachment attachment) {
    FileRef fileRef = attachment.getFile();
    downloader.download(fileRef);
}

Downloading Arbitrary Resources

The download() method can accept byte arrays, which allows you to download files or any other content. You should pass the byte array itself, the target file name and an optional format, for example:

@Autowired
private Downloader downloader;

private void downloadByteArray(byte[] content) {
    downloader.download(content, "notes.txt", DownloadFormat.TEXT);
}

To use a format not present in the DownloadFormat constants, create a new instance of DownloadFormat and pass it to the download() method, for example:

@Autowired
private Downloader downloader;

private void downloadByteArrayInCustomFormat(byte[] content) {
    DownloadFormat format = new DownloadFormat("application/data", "dat");
    downloader.download(content, "some-file.dat", format);
}

The download() method can also accept a lambda which returns an InputStream to download the content of this stream. For example:

@Autowired
private Downloader downloader;

private void downloadInputStreamContent(InputStream inputStream) {
    downloader.download(() -> inputStream, "archive.zip");
}

Displaying Files in UI Views

Jmix provides two UI components for embedding content into UI views:

  • image allows you to display images from various resources using the HTML <img> element. The component can be declaratively bound to an entity attribute to display images stored as byte arrays in the database or as files in the file storage.

  • iframe allows you to embed content inside the HTML <iframe> element.