To-Read sites 4.0
Sometimes, when creating web application, we want to enable user to upload files to a server.
The uploaded file can be an image, document or any other regular file. Developing our application using Spring should be relatively simple, so we need simple method for uploading files using this beautiful framework :-).
In our example I’ll use a Company
entity, which among the others will contain an Image
object with Data of the image and its name.
My Company entity looks like this:
|
|
As you can see I need company Address
, Name
and Image
.
In this example image is identified by name and data (content of image file), but you can do whatever you want with uploaded data, during conversion process.
On Spring Framework’s documentation sites we can see a usage of custom editor support to convert file uploaded using HTML form into regular Java object.
I went in a different way and used ConversionService
to easily convert file from HTTP POST request, which is more comfortable for me.
If you want to use ConversionService
you’ll need to create a converter, which implements org.springframework.core.convert.converter.Converter
interface.
Let’s create converter then:
|
|
We need to register our converter in conversion service, so in application context we add:
|
|
I use annotation-based configuration of controllers, so configuration of controller is pretty straightforward:
|
|
Going this way we have company
object with filled data from HTML form.
To obtain image data we just need to invoke e.g. company.getImage().getName();
The main advantage of this solution is its simplicity. You don’t need to create configuration of editors in your controller. All you need is to create a converter and register it in ConversionService. Spring will do all other stuff for you.
I hope it will help simplifying your web app :-).