<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>1048456</value>
</property>
<!--resolveLazily属性启用是为了推迟文件解析,以便在UploadAction 中捕获文件大小异常-->
<property name="resolveLazily" value="true"/>
</bean>
action 代码
public void upload(HttpServletRequest request) throws Exception{
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
List<MultipartFile> files = multipartRequest.getFiles("files");
for(MultipartFile file:files){
if (file == null || file.isEmpty()) {
//throw new Exception("请选择图片");
continue;
}
String fileName = file.getOriginalFilename();
List<String> imgTypes = new ArrayList<String>();
imgTypes.add("jpg");
imgTypes.add("png");
imgTypes.add("jpeg");
imgTypes.add("gif");
String imgType = fileName.substring(fileName.indexOf(".")+1, fileName.length());
if(!imgTypes.contains(imgType)){
throw new Exception("不支持."+imgType+"格式");
}
String path = request.getRealPath("/");
if(fileName.contains("mendian")){
path += "/img/"+fileName;
}
if(fileName.contains("cities_")){
path += "/www2/imgs/"+fileName;
}
File f = new File(path);
InputStream is = file.getInputStream();
OutputStream os = new FileOutputStream(f);
byte buff[] = new byte[1024];
int b ;
while((b = is.read())!=-1){
os.write(b);
}
}
}
异常处理方法
@ExceptionHandler(Exception.class)
public ModelAndView handleException(Exception ex,HttpServletRequest request) {
Map<Object, Object> model = new HashMap<Object, Object>();
if (ex instanceof MaxUploadSizeExceededException){
model.put("errors", "文件应不大于 "+
getFileKB(((MaxUploadSizeExceededException)ex).getMaxUploadSize()));
} else{
model.put("errors", "错误: " + ex.getMessage());
}
return new ModelAndView("/admin/wxManageAddorUpdate", (Map) model);
}
private String getFileKB(long byteFile){
if(byteFile==0)
return "0KB";
long kb=1024;
return ""+byteFile/kb+"KB";
}
页面代码
<body>
<div id="editDiv"></div>
<form method="post" action="<%=path %>/admin/storeMap.do?method=upload" enctype="multipart/form-data">
<input type="file" name="files"></input>
<input type="file" name="files"></input>
<input type="submit" value="提交"></input>
</form>
</body>
</html>