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:
package com.vaadin.demo.fusion.upload;
import java.util.UUID;
import org.jspecify.annotations.NonNull;
import org.springframework.web.multipart.MultipartFile;
import com.vaadin.flow.server.auth.AnonymousAllowed;
import com.vaadin.hilla.BrowserCallable;
@BrowserCallable
@AnonymousAllowed
public class UploadService {
/**
* Simulates uploading a file.
*
* @param file the uploaded file
* @return an identifier for the uploaded file
*/
@NonNull
public String uploadFile(@NonNull MultipartFile file) {
// handle the file as needed
return file.getOriginalFilename() + '_' + file.getSize() + '_' + UUID.randomUUID();
}
}
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.