Spring MVC failed to convert property value in file upload form

Problem

In Spring MVC application, while clicking on the file upload button, it hits the following property type conversion error?


Failed to convert property value of type [org.springframework.web.multipart.commons.CommonsMultipartFile] to required type [byte[]] for property file; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [org.springframework.web.multipart.commons.CommonsMultipartFile] to required type [byte] for property file[0]: PropertyEditor [org.springframework.beans.propertyeditors.CustomNumberEditor] returned inappropriate value

Here’s the SimpleFormController …


public class FileUploadController extends SimpleFormController{
	
	public FileUploadController(){
		setCommandClass(FileUpload.class);
		setCommandName("fileUploadForm");
	}
	//...
	
public class FileUpload{
	
	byte[] file;
	//...
}

Solution

This is a common issue in handling the uploaded file in Spring MVC, which is unable to convert the uploaded file into byte arrays automatically. To make it work, you have to register a custom editor (ByteArrayMultipartFileEditor) in the SimpleFormController’s initBinder() method to guide Spring to convert the uploaded file into byte array.


    public class FileUploadController extends SimpleFormController{
	
	public FileUploadController(){
		setCommandClass(FileUpload.class);
		setCommandName("fileUploadForm");
	}
	
       @Override
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)
		throws ServletException {
		
		// Convert multipart object to byte[]
		binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
		
	}
	//...

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
HibaHasan
4 years ago

thank you so much sooooo simple yet so helpful i was literally struggling!

Nasir
13 years ago

How to handle this situation in @Annotated Controllers..?

Cyper
13 years ago
Reply to  Nasir

define a method annotated with @InitBinder,like this:

@InitBinder
protected void initBinder(HttpServletRequest request,
	ServletRequestDataBinder binder) throws ServletException {
		binder.registerCustomEditor(byte[].class,
			new ByteArrayMultipartFileEditor());
}
Naveen Kumar Mishra
11 years ago
Reply to  Cyper

As this method is called automatically after that where the controller will be forwarded.