思路如下:
1.实现多文件上传
实现多文件上传非常简单,前台多个<input type="file">控件使用同一个名字,后台只需使用MultipartFile[]即可,代码如下
@RequestMapping("upload")
public String upload(@RequestParam(value=("file"),required=false) MultipartFile[] files) throws IOException{
//判断file数组不能为空并且长度大于0
if(files!=null&&files.length>0){
//循环获取file数组中得文件
for(int i = 0;i<files.length;i++){
MultipartFile file = files[i];
//保存文件
FileUtils.writeByteArrayToFile(new File("D:\\"+file.getOriginalFilename()), file.getBytes());
}
}
return "redirect:/index.jsp";
}
2.实现进度条
由于SpringMVC上传组件是基于commons-fileupload组件,所以需要实现ProgressListener监听器,来监听文件上传状态,并实现Update()
@Override
public void update(long bytesRead, long contentLength, int items) {
double MBRead = bytesRead / 1021 / 1024;//防止溢出,不进行强制转换
double MBLength = contentLength / 1024 /1024;
double result = MBRead / MBLength * 100;
BigDecimal b = new BigDecimal(result);
status.setPercent(b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
status.setItems(items);
session.setAttribute("status",status);
}
但是SpingMVC上传组件并没有预留该监听器接口,所以需要扩展CommonsMultipartResolver类,并重写parseRequest()(
从网上搜索资料说明要重写newFileUpload()用来添加监听器和resolveMultipart()来设置request,而经过调试我发现newFIleUpload在项目启动是就会调用,而resolveMultipart()则会在文件上传时调用,所以不可能通过resolveMultipart()来获取request以供newFileUpload使用。)
<span style="font-family: Verdana; background-color: rgb(226, 226, 226);"></span><pre name="code" class="java"> public MultipartParsingResult parseRequest(HttpServletRequest request)
throws MultipartException {
String encoding = "utf-8";//设置编码
FileUpload fileUpload = prepareFileUpload(encoding);
final HttpSession session = request.getSession();
UploadStatus status = new UploadStatus();
fileUpload.setProgressListener(new ProgressListenerImpl(status, session));
try {
List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
return parseFileItems(fileItems, encoding);
} catch (FileUploadBase.SizeLimitExceededException ex) {
throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(),ex);
} catch (FileUploadException ex) {
throw new MultipartException("Could not parse multipart servlet request", ex);
}
}
3.使用Ajax获取Session中存储的status对象