Controller类中:
//@RequestParam:数组的注解,
@RequestMapping(value="add",method=RequestMethod.POST)
public String add(@Validated User users,BindingResult br,
@RequestParam(value="attachs") MultipartFile attachs[],
HttpServletRequest request) throws IOException{
//你需要验证的对象后边要紧跟BindingResult
if(br.hasErrors()){//有错误,不提交。相当于异常回滚
return "user/addUser";
}
for(MultipartFile attach:attachs){
if(!attach.isEmpty()){
//上传单个文件,添加附件
//上传的路径:
String realName=request.getSession().
getServletContext().getRealPath("/statics/upload");
//File.separator:自动辨别电脑系统:用该为"/"还是"\"
File file=new File(realName+File.separator+attach.
getOriginalFilename());
//上传:
FileUtils.copyInputStreamToFile(attach.getInputStream(),
file);
System.out.println("===============>");
System.out.println(attach.getName());
System.out.println(attach.getOriginalFilename());
System.out.println(attach.getContentType());
}
}
映射文件中添加以下内容:
<!-- 文件上传 :-->
<!-- id的值必须为:multipartResolver -->
<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="500000"/>
</bean>
jsp页面添加相应的添加按钮即可
版权声明:本文为博主原创文章,未经博主允许不得转载。