1.导入jar包
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.0</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2.springmvc.xml
<!-- 配置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="1024000"></property>
</bean>
注意:如果提示文件找不到(404)需要修改springmvc.xml配置文件,加上以下配置
<mvc:default-servlet-handler/>
3.单个上传
<br><br>
<h4>单个文件上传</h4>
<form action="springmvc/testFileUpload" method="post" enctype="multipart/form-data">
File:<input type="file" name="file"/>
<input type="submit" value="Submit">
</form>
<br><br>
//单个
@RequestMapping("/testFileUpload")
public String fileupload(ServletRequest request, @RequestParam("file") MultipartFile file, Model model)
throws IOException {
if (!file.isEmpty()) {
String imageurl = saveFile(request, file);
model.addAttribute("imageurl", imageurl);
} else {
model.addAttribute("message", "请选择要上传的文件");
}
return "fileupload";
}
//单个
private String saveFile(ServletRequest request, MultipartFile file) throws IOException {
// 获取文件的上传路径
String uploadPath = request.getServletContext().getRealPath("uploads");
File uploadPathFile = new File(uploadPath);
if (!uploadPathFile.exists()) {
uploadPathFile.mkdirs();
}
// 获取文件名称
String filename = file.getOriginalFilename();
// 截取文件后缀
String fileext = filename.substring(filename.lastIndexOf("."));
// 生成新的随机文件名称
String newfileName = UUID.randomUUID() + fileext;
// 文件保存路径
File savePath = new File(uploadPath + "/" + newfileName);
System.out.println("savePath路径+"+savePath);
// 上传文件
file.transferTo(savePath);
return "uploads/" + newfileName;
}
4.多个上传
<br><br>
<h4>多个文件上传</h4>
<form action="springmvc/filesupload" method="post" enctype="multipart/form-data">
<input type="file" name="file" /><br><br>
<input type="file" name="file" /><br><br>
<input type="file" name="file" /><br><br>
<input type="submit" value="上传" />
<br />
</form>
<br><br>
//多个
@RequestMapping("/filesupload")
public String filesupload(ServletRequest request, @RequestParam("file") MultipartFile[] files, Model model) throws IOException{
List<String> images = new ArrayList<String>();
if(files!=null && files.length > 0){
for (int i = 0; i < files.length; i++) {
images.add(this.saveFile(request, files[i]));
}
model.addAttribute("images", images);
}
return "filesupload";
}