5

This code is a RestEasy code for handling upload:

@Path("/fileupload")
public class UploadService {
    @POST
    @Path("/upload")
    @Consumes("multipart/form-data")
    public Response create(@MultipartForm FileUploadForm form) 
    {
       // Handle form
    }
}

Is there anything similar using Spring that can handle MultipartForm just like this?

quarks
  • 33,478
  • 73
  • 290
  • 513

2 Answers2

2

Spring includes has a multipartresolver that relies on commons-fileupload, so to use it you have to include it in your build.

In your applicationContext.xml

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="<max file size>"/>
</bean>

In your controller, use org.springframework.web.multipart.MultipartFile.

@RequestMapping(method=RequestMethod.POST, value="/multipartexample")
public String examplePost(@RequestParam("fileUpload") MultipartFile file){
    // Handle form upload and return a view
    // ...
}
pap
  • 27,064
  • 6
  • 41
  • 46
  • The MutipartFile have the 'path' and 'id' attribute automatically parsed from the request? – quarks Sep 24 '12 at 11:53
  • If you are referring to the path to the file at the clients computer and the "id" attribute of the input tag, then no. Those are not sent to the server at all, ever. – pap Sep 24 '12 at 11:57
  • Ok... I will try this and hopefully it will work with App Engine. – quarks Sep 24 '12 at 12:08
  • Made a small edit - use `@RequestParam` instead of `@ModelAttribute` – pap Sep 24 '12 at 12:12
0

Here is an example showing how you could use MVC Annotations to achieve something similar in Spring:

@RequestMapping(method=RequestMethod.POST, value="/multipartexample")
public String examplePost(@ModelAttribute("fileUpload") FileUpload fileUpload){
    // Handle form upload and return a view
    // ...
}

@InitBinder
public void initBinder(ServletRequestDataBinder binder) {
    binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
}

public class FileUpload implements Serializable {
    private MultipartFile myFile;

    public MultipartFile getMyFile() {
        return myFile;
    }

    public void setMyFile(MultipartFile myFile) {
        this.myFile = myFile;
    }
}

You should be able to post to this endpoint from the html form, assuming the name of the file element is 'myFile'. Your form could look like the following:

<form:form commandName="fileUpload" id="fileUploadForm" enctype="multipart/form-data">
    <form:input type="file" path="myFile" id="myFile"/>
</form:form>

The @InitBinder code is important because it instructs Spring to convert the files to a byte array, which can then be turned into the MultipartFile

Matt
  • 3,455
  • 1
  • 17
  • 6