Handling MultipartForm with Spring

This code is the RestEasy code to handle the download:

@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 MultipartFormjust like that?

+5
source share
2 answers

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

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
    // ...
}
+2
source

Here is an example showing how you can 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;
    }
}

html-, , "myFile". :

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

@InitBinder , Spring , MultipartFile

0

All Articles