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 screens.
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:
@JmixEntity
@Table(name = "PERSON")
@Entity
public class Person {
// ...
@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 on the screen. For example:
<data>
<instance id="personDc"
class="files.ex1.entity.Person">
<fetchPlan extends="_base"/>
<loader/>
</instance>
</data>
<layout spacing="true">
<form dataContainer="personDc">
<column>
<textField id="nameField" property="name"/>
<fileUpload id="photoField" property="photo"/> (1)
</column>
<column>
<image dataContainer="personDc" property="photo"
height="300" width="300" scaleMode="CONTAIN"/> (2)
<linkButton id="downloadBtn" caption="Download"/>
</column>
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:
@Autowired
private InstanceContainer<Person> personDc;
@Autowired
private Downloader downloader; (1)
@Subscribe("downloadBtn")
public void onDownloadBtnClick(Button.ClickEvent 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. |