jsp代码
<form action="upload" enctype="multipart/form-data" method="post">
上传用户:<input type="text" name="username"><br/>
上传文件1:<input type="file" name="file1"><br/>
上传文件2:<input type="file" name="file2"><br/>
<input type="submit" value="提交">
</form>
后台代码如下:
@RequestMapping("/upload")
public String upload(MultipartFile file, HttpServletRequest req,ModelMap modelMap) {
String path = req.getSession().getServletContext().getRealPath(
"fileupload");
String filename = file.getOriginalFilename();
System.out.println(path);
File tfile = new File(path, filename);
//判断指定路径下的文件目录是否存在
if (!tfile.exists()) {
//不存在的话创建目录文件
tfile.mkdirs();
}
try {
//转存文件
file.transferTo(tfile);
} catch (Exception e) {
e.printStackTrace();
}
modelMap.addAttribute("fileUrl", req.getContextPath() + "/fileupload/"
+ filename);
return "hello";
}
批量上传
@RequestMapping("/uploadFiles")
public String uploadFiles(@RequestParam("file")MultipartFile file[], HttpServletRequest req,
ModelMap modelMap) {
String path = req.getSession().getServletContext().getRealPath(
"fileupload");
for (int i = 0; i < file.length; i++) {
String filename = file[i].getOriginalFilename();
System.out.println(path);
File tfile = new File(path, filename);
//判断指定路径下的文件目录是否存在
if (!tfile.exists()) {
//不存在的话创建目录文件
tfile.mkdirs();
}
try {
//转存文件
file[i].transferTo(tfile);
} catch (Exception e) {
e.printStackTrace();
}
}
modelMap.addAttribute("fileUrl", "文件上传成功");
return "hello";
}