前端JSP页面代码
<label>附件:</label>
<form id="fileForm">
<input type="file" name="files" multiple="multiple" >
<input type="button" id="btn_add_file" value="上传附件" onclick="upload_files()">
</form>
<script>
function upload_files(){
var formData = new FormData($("#fileForm")[0]);
$.ajax({
url : path.basePath+"file/uploadFiles2.do",
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success : function(data) {
alert("成功了!"+data);
},
error : function(data) {
alert("失败了!"+data);
}
});
</script>
java springMVC后台代码
@RequestMapping(value = "uploadFiles2.do", method = RequestMethod.POST)
@ResponseBody
public String uploadFiles2(@RequestParam(value="files")List<MultipartFile> list,HttpServletRequest request) {
System.out.println("**************************进入uploadFiles2方法*********************************");
Map<String,String> map = new HashMap<String,String>();
try {
for (MultipartFile file : list) {
String fileName = file.getOriginalFilename();
String saveName = UUID.randomUUID().toString().replace("-","") + fileName.substring(fileName.lastIndexOf("."));
String savedPath = request.getSession().getServletContext().getRealPath("/uploadFiles/");//获取服务器指定文件存取路径
File saveDir = new File(savedPath);
if (!saveDir.exists()){
saveDir.mkdirs();
}
File saveFile = new File(savedPath, saveName);
System.out.println(saveFile);
map.put(fileName,saveFile.toString());
file.transferTo(saveFile);
}
return map.toString();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}