前言:接触springmvc不久,遇到一些问题总是很让人烦恼,这里把一些简单的东西记录一下。
正文:对于文件上传,spring已经包装得很好了,对于目前的我来说,几乎没什么好挑剔的。
也很简单,大概copy一下程序吧,用的是spring官方文档里的。
在MultipartResolver 完成分段文件解析后,这个请求就会和其它请求一样被处理。为了使用文件上传,你需要创建一个带文件上传域(upload field)的(HTML)表单,让Spring将文件绑定到你的表单上(如下所示):
<html>
<head>
<title>Upload a file please</title>
</head>
<body>
<h1>Please upload a file</h1>
<form method="post" action="upload.form" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</form>
</body>
</html>
总而言之,为了使用表单上传文件,你需要声明一个解析器,一个控制器,再将文件上传的URL映射到控制器来处理这个请求。下面是这几个bean的声明。
<beans>
<!-- lets use the Commons-based implementation of the MultipartResolver interface -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
/upload.form=fileUploadController
</value>
</property>
</bean>
<bean id="fileUploadController" class="examples.FileUploadController">
<property name="commandClass" value="examples.FileUploadBean"/>
<property name="formView" value="fileuploadform"/>
<property name="successView" value="confirmation"/>
</bean>
</beans>
在下面这个例子里,上传的文件被绑定为(表单支持的)对象(form backing object)的String属性:
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
String file = bean.getFile();
if (file == null) {
// hmm, that's strange, the user did not upload anything
}
// well, let's do nothing with the bean for now and return
return super.onSubmit(request, response, command, errors);
}
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)
throws ServletException {
// to actually be able to convert Multipart instance to a String
// we have to register a custom editor
binder.registerCustomEditor(String.class, new StringMultipartFileEditor());
// now Spring knows how to handle multipart object and convert them
}
}
public class FileUploadBean {
private String file;
public void setFile(String file) {
this.file = file;
}
public String getFile() {
return file;
}
}
好了,相信跟着上面的配置后,简单加一点东西你就可以上传了。
但是在整合进公司项目时,我就出现问问多多了。
这看对整个springmvc的了解了。
一;是页面参数的获取,也就是file路径的获得:
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
CommonsMultipartFile mfile = (CommonsMultipartFile) multipartRequest.getFile("file");
可以使用CommonsMultipartFile 来读取到路径。
二;ModelAndView onSubmitt(Object command,HttpServletRequest request)
command参数不要忘记添加
三;注意一些名字之类的一致,基本没什么错误了。