1. 添加上传文件组件支持
复制代码
1
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
2. Controller部分
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@RequestMapping("upload.do")
public String upload(@RequestParam("file") MultipartFile file)
throws IllegalStateException, IOException {
String basePath = "xxx";
String path = "";
if (!file.isEmpty()) {
if (file.getOriginalFilename().endsWith("txt"))
path = basePath + "doc";
else if (file.getOriginalFilename().endsWith("jpg") || file.getOriginalFilename().endsWith("gif")
|| file.getOriginalFilename().endsWith("png"))
path = basePath + "img";
else
path = basePath + "other";
String fileName = f.getOriginalFilename();
File tarFile = new File(path, fileName);
file.transferTo(tarFile);
}
return "index.jsp";
}
3. html部分
复制代码
1
2
3
4
<form action="upload.do" enctype="multipart/form-data" method="post">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
4. 多文件上传
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@RequestMapping("upload.do")
public String upload(@RequestParam("file") MultipartFile[] file, HttpServletRequest req)
throws IllegalStateException, IOException {
String basePath = "xxx";
for (MultipartFile f : file) {
String path = "";
if (!f.isEmpty()) {
if (f.getOriginalFilename().endsWith("txt"))
path = basePath + "doc";
else if (f.getOriginalFilename().endsWith("jpg") || f.getOriginalFilename().endsWith("gif")
|| f.getOriginalFilename().endsWith("png"))
path = basePath + "img";
else
path = basePath + "other";
String fileName = f.getOriginalFilename();
File tarFile = new File(path, fileName);
f.transferTo(tarFile);
}
}
return "index.jsp";
最后
以上就是个性香菇最近收集整理的关于【JavaWeb】SpringMvc 文件上传的全部内容,更多相关【JavaWeb】SpringMvc内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复