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

4 comments on “Spring MVC failed to convert property value in file upload form

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

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

    Reply
    1. define a method annotated with @InitBinder,like this:

      @InitBinder
      protected void initBinder(HttpServletRequest request,
      	ServletRequestDataBinder binder) throws ServletException {
      		binder.registerCustomEditor(byte[].class,
      			new ByteArrayMultipartFileEditor());
      }
      
      Reply
      1. As this method is called automatically after that where the controller will be forwarded.

        Reply

Leave a Comment

Your email address will not be published. Required fields are marked *