package fileupload;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.springframework.validation.*;
import org.springframework.web.bind.*;
import org.springframework.web.multipart.support.*;
import org.springframework.web.servlet.*;
import org.springframework.web.servlet.mvc.*;
// snippet from FileUploadController
public class FileUploadController extends SimpleFormController {
protected ModelAndView onSubmit(
HttpServletRequest request,
HttpServletResponse response,
Object command,
BindException errors) throws ServletException, IOException {
// cast the bean
FileUploadBean bean = (FileUploadBean) command;
// let's see if there's content there
byte[] file = bean.getFile();
if (file.length == 0) {
// hmm, that's strange, the user did not upload anything
return new ModelAndView(this.getFormView());
}
// well, let's do nothing with the bean for now and return:
File myFile = new File("myfile.txt");
myFile.createNewFile();
try {
return super.onSubmit(request, response, command, errors);
} catch (Exception ex) {
return null;
}
}
protected void initBinder(
HttpServletRequest request,
ServletRequestDataBinder binder) throws ServletException {
// to actually be able to convert Multipart instance to byte[]
// we have to register a custom editor (in this case the
// ByteArrayMultipartEditor
binder.registerCustomEditor(byte[].class,
new ByteArrayMultipartFileEditor());
// now Spring knows how to handle multipart object and convert them
}
} |