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:

@Entity
@Table
public class Company {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;
	@ManyToOne(cascade = CascadeType.ALL)
	private Address address;
	@NotEmpty
	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> {
	@Override
	public Image convert(final MultipartFile source) {
		final Image image = new Image();
                image.setData(source.getBytes());
		image.setName(source.getOriginalFilename());
		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">
		<set>
			<bean class="pl.greenpath.converter.MultipartFileToImageConverter">
		</set>
	</property>
</bean>

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

        @Autowired
        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 {
			_companyService.save(company);
			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
    jD

  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!

    Roogards
    jD

  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

    Hej,
    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.

    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=""> <strike> <strong>