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());
		
	}
	//...

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
2 Comment threads
2 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
3 Comment authors
Naveen Kumar MishraCyperNasirSpring MVC Tutorials Recent comment authors
newest oldest most voted
Nasir
Guest
Nasir

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

Cyper
Guest
Cyper

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
Guest
Naveen Kumar Mishra

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

trackback
Spring MVC Tutorials

[…] Spring MVC failed to convert property value in file upload form […]