Search code examples
javaspringjspspring-mvcapache-commons

Uploading file using Spring MVC and CommonsMultipartResolver not working as expected


I am trying to upload files using Spring CommonsMultipartResolver however the controller is not recognised. I get this errror message: "The requested resource (/WebIDE/WEB-INF/views/file/upload.jsp) is not available."

I have added commons-fileupload-1.2.2.jar and commons-io.1.3.2.jar in my library. I have added the following in my application context:

<context:component-scan base-package="org.webide.mvc" />

<bean id="multipartResolver"
  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

  <!-- specify maximum file size in bytes -->
  <property name="maxUploadSize" value="100000"/>
</bean>

I'm using Pojo as my controller:

@Controller
@RequestMapping (value = "/file")
public class FileController {

  @RequestMapping (value = "/upload")
  public String uploadFile(@RequestParam("file") CommonsMultipartFile file){
    if (!file.isEmpty()){
      byte fileBytes[] = file.getBytes();
      return "mainView";
    }else{
      return "errorView";
    }
  }

My html is quite simple at the moment:

<form method="post" action="file/upload" enctype="multipart/form-data">
            <input type="text" name="name"/>
            <input type="file" name="file"/>
            <input type="submit"/>
</form>

Could you please let me know if I am missing something? Thanks


Solution

  • The main URL was http://localhost:8084/WebIDE/, then action="/file/upload" should send request to class marked with @Controller. I put a breakpoint and it was not picking up the controller at all.

    I had to change my spring configuration to copy everything specified in application context (see above) to dispatcher servlet mvc-config.xml, and also change the way I was declaring them so that the context is the parent of mvc-config.xml

    Looks like it did the trick! :)

    Thanks again for your help and suggestions.