Expert Spring MVC and Web Flow

(Dana P.) #1
</bean>

</beans>

Note that we declared the multipart resolver in the same ApplicationContextas our
Controller. We recommend grouping all web-related beans in the same context.
Next, we create the form for the file upload, as shown in Listing 5-41.

■Tip It’s very important to set the enctypeattribute of the

element to multipart/form-data.


Listing 5-41.HTML File Upload Form

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>File Upload Form</title>
</head>
<body>

<form action="spring/handleUpload" method="post" enctype="multipart/form-data">

File: <input type="file"name="uploaded" />

<input type="submit" />

</form>
</body>
</html>

The Controllerthat handles the request is shown in Listing 5-42. Notice how it must cast
the request object to a MultipartHttpServletRequestbefore extracting the file. The utility class
FileCopyUtils, provided by Spring, contains convenience methods such as copying an input
stream to an output stream.

Listing 5-42.File Upload Controller

public class HandleUploadController extends AbstractController
implements InitializingBean {

private File destinationDir;

public void setDestinationDir(File destinationDir) {
this.destinationDir = destinationDir;
}

110 CHAPTER 5 ■THE PROCESSING PIPELINE

Free download pdf