Expert Spring MVC and Web Flow

(Dana P.) #1
public void afterPropertiesSet() throws Exception {
if (destinationDir == null) {
throw new IllegalArgumentException("Must specify destinationDir");
} else if (!destinationDir.isDirectory() && !destinationDir.mkdir()) {
throw new IllegalArgumentException(destinationDir + " is not a " +
"directory, or it couldn't be created");
}
}

protected ModelAndView handleRequestInternal(HttpServletRequest req,
HttpServletResponse res) throws Exception {
res.setContentType("text/plain");

if (! (req instanceof MultipartHttpServletRequest)) {
res.sendError(HttpServletResponse.SC_BAD_REQUEST,
"Expected multipart request");
return null;
}

MultipartHttpServletRequest multipartRequest =
(MultipartHttpServletRequest) req;
MultipartFile file = multipartRequest.getFile("uploaded");
File destination = File.createTempFile("file", "uploaded",
destinationDir);
FileCopyUtils.copy(file.getInputStream(),
new FileOutputStream(destination));

res.getWriter().write("Success, wrote to " + destination);
res.flushBuffer();
return null;
}

}


If you are creating command beans (see BaseCommandControllerand SimpleFormController
in Chapter 6) to encapsulate the request parameters from forms, you can even populate a prop-
erty of your command object from the contents of the uploaded file. In other words, instead
of performing the manual operation of extracting the file from the MultipartFileinstance (as
we did in the preceding example in Listing 5-42), Spring MVC can inject the contents of the
uploaded file (as a MultipartFile, byte[], or String) directly into a property on your command
bean. With this technique there is no need to cast the ServletRequestobject or manually retrieve
the file contents.


CHAPTER 5 ■THE PROCESSING PIPELINE 111
Free download pdf