js:
jquery-form.js
jsp:
<form id="form_serviceFile" action="javascript(0);" method="post" enctype="multipart/form-data">
<div class="div-box div-panel">
<div class="div-panel-title">文件框</div>
<div class="div-item">
<span class="item-title">文件1:</span>
<span><input type="file" class="file_service" id="file_service1" name="file_service1"/></span>
</div>
<div class="div-item">
<span class="item-title"><!-- <input id="submit_serviceFile" type="button" value="上传"/> -->
<input type="button" οnclick="submitFile(1)" value="上传"/>
<!-- <input type="submit" value="上传" /> --> </span>
</div>
<div style="clear:both;"></div>
</div>
</form>
javascript:
$(".file_service").each(function(){
// 验证当前form下的多个文件
if($(this).val() == "") {
alert("请从文件1开始上传维修文件!");
$(this).val() == "";
return false;
}
$("#form_serviceFile").ajaxSubmit({
type:'post',
url:'<%=basePath %>uploadFile/uploadFileDefService.do?fileType=serviceFile',
success:function(data){
if(data.type=1){
$.messager.alert('文件上传','维修附件上传成功!');
}
}
});
return false;
});
controller:
@ResponseBody
@RequestMapping(value="/uploadFile/uploadFileDefService.do",method=RequestMethod.POST)
public ControllerBean uploadFile(HttpServletRequest req,String fileType){
ControllerBean retValue = new ControllerBean(ControllerBean.TYPE_ERROR,"上传失败!");
//1.设置存放目录
String realPath = req.getServletContext().getRealPath("upload");
//String realPath = "D:/image/upload";
File f = new File(realPath);
if(!f.exists()){
f.mkdir();
}
CommonsMultipartResolver resolver= new CommonsMultipartResolver(req.getServletContext());
String allPath =null;
if(resolver.isMultipart(req)){
MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest)req;
//获取所有文件名
Iterator<String> fileNames = multipartRequest.getFileNames();
int index = 0;
while (fileNames.hasNext()) {
//取得指定文件名的文件
MultipartFile file = multipartRequest.getFile(fileNames.next());
//获取原始文件名
String originalFilename = file.getOriginalFilename();
//创建一个时间格式,用于保存
SimpleDateFormat sf=new SimpleDateFormat("yyyyMMddHHmmssSSS");
String time = sf.format(new Date());
String timePath =time+originalFilename;
//路径+日期重组文件名 File.separator相当于地址分隔符 /
String path = realPath+File.separator+timePath;
try {
//将文件存到指定目录
file.transferTo(new File(path));
if(index == 0){
allPath =timePath;
}else{
allPath+="*"+timePath;
}
index++;
}catch (Exception e) {
e.printStackTrace();
}
}
retValue.setType(ControllerBean.TYPE_SUCCESS);
retValue.setMsg("上传成功!");
}
return retValue;
}