Spring Framework – file upload using ConversionService

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:

public class Company {
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;
	@ManyToOne(cascade = CascadeType.ALL)
	private Address address;
	private String name;
	@OneToOne(cascade = CascadeType.ALL)
	private Image image;
... accessors ommitted

As you can see I need company Address, Name and the 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:

import org.springframework.core.convert.converter.Converter;
import org.springframework.web.multipart.MultipartFile;
public class MultipartFileToImageConverter implements Converter<MultipartFile, Image> {
	public Image convert(final MultipartFile source) {
		final Image image = new Image();
		return image;

We need to register our converter in conversion service, so in application context we add:

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
	<property name="converters">
			<bean class="pl.greenpath.converter.MultipartFileToImageConverter">

I use annotation-based configuration of controllers, so configuration of controller is pretty straightforward:

        CompanyService _companyService;
	@RequestMapping(value = "", method = RequestMethod.POST)
	public String doEdit(@Valid final Company company, final Errors errors) {
		if (errors.hasErrors()) {
			return "admin/companies/edit";
		} else {
			return "redirect:/admin/companies/" + company.getId();

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 😉

  1. Hello Michat,
    This is a very clean approach for dealing with uploading files (images) using the Spring framework…

    I created a Spring Roo web app implementing the same functionality. I think, I am going to update it using your approach.

    If interested you can visit my blog on it at: http://viralpatel.net/blogs/2011/02/spring-roo-save-read-blob-object-spring-roo-tutorial.html.

    A last thing… I am curious about the Image class details. What is the type of the data field that you are using?

    Thank you and B. Roogards

  2. Michał Borek

    Hello jD!
    Thanks for your comment.

    I’ll take a look into your solution and I’ll be probably using it :) Please tell me when you implement solution similar to mine and I can link to it on my blog.

    If it comes to my solution with Image object in Company I think in production I’ll use slightly different approach and I’ll store file on some static http server so I don’t need to use blobs at all. Then I won’t use “data” attribute but just link to static content.

    Either way it can be also done in a converter :)

    Btw. It’s rather MichaL not Michat :) (Kind of Michael:))

  3. MichaL,

    For some reason the ł on “Michał Borek says:” looks with a crossed tilde or something. That confused me. But, I got it now: MichaL not Michat.

    My similarity comment is on regard to a Spring web app uploading documents, images or blobs. I mentioned in that context and I gave you my link already.

    On static vs blobs I’ve seen developers interested in both implementations. I will update my solution for covering both use cases.

    If interested on more of my stuff you can visit my blog at http://pragmatikroo.blogspot.com

    Feedback is always welcome!


  4. Szanowny Panie. Niestety nie znalazłem innej formy kontaktu, dlatego piszę ten komentarz w tym miejscu. Czy mógłbym prosić o zaktualizowanie rozszerzenia Opery “to-read”, aby współpracowało z najnowszą wersją Opera 15? Developrzey Opery piszą, że jest to bardzo proste i mało czasochłonne. Tylko z powodu braku “to-read” na Operze 15 ciągle siedzę na wersji Opera 12.

  5. Michał Borek

    Aktualnie Opera ma problemy z aktualizacją mojej wtyczki (jakiś techniczny problem z konwerterem lub ich serwerem). Napisałem już do nich i mam nadzieję, że poprawią konwerter. Jak tylko to się stanie, wtyczka będzie dostępna w nowej wersji.


  6. Convert Uploaded File to POJO - BlogoSfera - pingback on 2015/08/22 at 00:27
  7. Panie Michale, stało się coś strasznego – wtyczka przestała działać prawidłowo i straciłem swoje “strony do przeczytania”. Czy jest sposób aby je odzyskać? Gdzie są zapisywane strony? Pozdrawiam!

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Trackbacks and Pingbacks: