Storing Files in Database

In this section, we will give an example of uploading and saving images to the application database. In addition, we will describe how images can be displayed in Jmix UI views.

Save only small files in the database: thumbnails, icons, etc., because the whole file is placed in memory when it is uploaded or downloaded.

Firstly, create an attribute of the byte array (byte[]) type in your entity, for example:

@Column(name = "PHOTO")
private byte[] photo;

public byte[] getPhoto() {
    return photo;
}

public void setPhoto(byte[] photo) {
    this.photo = photo;
}

When you run the application, Studio generates a database migration script for creating a corresponding column of the type appropriate for your database. For example, for PostgreSQL it is bytea.

For uploading the file from a user interface, use the fileUploadField component bound to the entity attribute. If the file is an image, you can use the image component to display the image in the view. For example:

<formLayout id="form" dataContainer="personDc">
    <textField id="nameField" property="name"/>
    <vbox>
        <hbox>
            <fileUploadField id="photoField" property="photo"/> (1)
            <button id="downloadBtn" text="Download"/>
        </hbox>
        <image id="image" dataContainer="personDc" property="photo"/> (2)
    </vbox>
</formLayout>
1 fileUploadField component allows users to upload a file and store it in an entity attribute.
2 image component displays the content of the entity attribute.

If you want to be able to download the file, add a button and define its click handler as follows:

@ViewComponent
private InstanceContainer<Person> personDc;

@Autowired
private Downloader downloader; (1)

@Subscribe("downloadBtn")
public void onDownloadBtnClick(final ClickEvent<Button> event) {
    byte[] photo = personDc.getItem().getPhoto();
    downloader.download(
            photo,
            personDc.getItem().getName() + "photo", (2)
            DownloadFormat.JPG (3)
    );
}
1 Use the Downloader bean to download files.
2 Define the downloaded file name.
3 If you know the file format, specify it in the last argument of the download() method. Depending on the format, the web browser either downloads the file or shows it in a tab.