Uploading & Downloading Files
Transferring files between the client and server is a common requirement in web applications. This page demonstrates how to implement file uploading and downloading in Hilla React applications.
Uploading Files
Hilla supports the MultipartFile class from Spring to handle file uploads. It maps to the standard File interface in the generated TypeScript code.
The following example demonstrates how to implement such a service and connect it to the Upload component in a view:
const handleUploadRequest = async (e: UploadRequestEvent) => {
e.preventDefault();
const uploadRef = e.target as UploadElement;
const fileId = await UploadService.uploadFile(e.detail.file);
uploadRef.files = uploadRef.files.map((file) => {
file.status = '';
file.complete = true;
return file;
});
Notification.show(`Received file: ${fileId}`);
};
return <Upload maxFiles={1} onUploadRequest={handleUploadRequest} />;
Downloading Files
Hilla endpoints only respond to POST
requests and don’t support file downloads. Since Hilla applications use Spring, though, you can leverage Spring’s capabilities to implement file downloading.
Select the server mapping that best suits your application. Then create an ad-hoc endpoint to handle file downloads.
Next, configure security using the usual Spring Security configuration semantics.
In the following example, the view downloads a file and passes an ID as a parameter. The endpoint generates the file and sends it to the client. The security is configured so that only authenticated users can download files.
const id = useSignal('');
return (
<div className="flex p-m gap-m items-end">
<TextField
label="ID"
value={id.value}
onValueChanged={(e) => {
id.value = e.detail.value;
}}
/>
{id.value && (
<a href={`/download/${id.value}`} download>
Download
</a>
)}
</div>
);