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!

  8. Michal,

    Just started using Opera 36.0 and “To Read” 5.0.

    The “To Read” type of function is my most valuable extension when I use Fire.. you know who). It makes the entire browsing experience much more efficient and pleasant.

    “To Read” is a very good effort, but here is where it falls short, in my opinion.

    Before I can add a page to “To Read” I have to take three steps:
    – actually load the page
    – click the “To Read” icon
    – confirm that I want to add it to “To Read”

    1) Loading the page takes time, even on my fast connection.
    2) If I wanted to read the page at that moment, I would go there and read it.
    3) Confirming that I really – really – actually – want to add it to the list, is just annoying. Why would I get that far along if I didn’t want to add it? Is it that destructive to add a page by mistake?

    Here is how I would like it to work:

    – Pass mouse over a link.
    – right-click to get a context menu
    – on context menu click “Add To Read”
    – It’s added to a “To Read” bookmark folder with no further action.
    – It can be seen as a folder under book marks.
    If a url is already in the “To Read” list, the context menu says, Remove from “To Read”.
    When a url is opened by clicking on it in the “To Read” list, it is automatically removed from the list.

    I’m well aware that this would be an immense rewrite, probably an entirely new extension, but it can be done. It would be very popular.

    To see it work the way I described, try the “Save-To-Read”extension in Fire.. (you know who). As I write this, it has 6,897 users and a 5 star rating.

    I will not use Pocket because of privacy issues. It wasn’t that way when they started, and before Pocket bought the original developer.

    Anyway, I do appreciate your effort.

    Thank you, and regards,


  9. Michał Borek

    Hello Stu,
    Thanks for using this extension!
    You idea is very good. I’ll think about this and I’ll try to find some time to implement it.

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: