1、首先,在pom.xml文件中添加相关依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
2、在spring mvc配置文件中增加一个文件上传bean
<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8" />
</bean>
3、contruller代码文件
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* @author lenovo
*/
@Controller
public class UploadDemoController {/**
* 上传单个文件
* 通过MultipartFile读取文件信息,如果文件为空跳转到结果页并给出提示;
* 如果不为空读取文件流并写入到指定目录,最后将结果展示到页面
* @param origFile
* @param
* @return
*/
@RequestMapping("/upload")
public String uploadSingleFile(@RequestParam("file") MultipartFile origFile,HttpServletRequest request
) {
if (origFile.isEmpty()) {
//redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "upload_result";
}
try {
String contentType = origFile.getContentType();
String fileName = origFile.getOriginalFilename();
byte[] bytes = origFile.getBytes();
System.out.println("上传文件名为-->" + fileName);
System.out.println("上传文件类型为-->" + contentType);
System.out.println("上传文件大小为-->"+bytes.length);
String filePath=ResourceUtils.getURL("classpath:").getPath();
File parentPath = new File(filePath,"imgupload");
System.out.println("上传目的地为-->"+parentPath.getAbsolutePath());
try {
//上传目的地
File destFile = new File(parentPath, fileName);
FileUtils.writeByteArrayToFile(destFile,origFile.getBytes());
} catch (Exception e) {
// TODO: handle exception
}
request.setAttribute("message", "You successfully uploaded '" + origFile.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "upload_result";
}
/**
* 上传多个文件,同时接受业务数据
* @param origFiles
* @param request
* @param user
* @return
*/
@RequestMapping("/uploadMultiFiles")
public String uploadMultiFiles(@RequestParam("file") List<MultipartFile> origFiles,HttpServletRequest request
,User user ) {
System.out.println("User=="+user);
if (origFiles.isEmpty()) {
return "upload_result";
}
try {
for (MultipartFile origFile : origFiles) {
String contentType = origFile.getContentType();
String fileName = origFile.getOriginalFilename();
byte[] bytes = origFile.getBytes();
System.out.println("上传文件名为-->" + fileName);
System.out.println("上传文件类型为-->" + contentType);
System.out.println("上传文件大小为-->"+bytes.length);
String filePath = "f:/myres";
System.out.println("上传目的地为-->"+filePath);
try {
File destFile = new File(filePath,fileName);//上传目的地
FileUtils.writeByteArrayToFile(destFile,origFile.getBytes());
} catch (Exception e) {
// TODO: handle exception
}
}
request.setAttribute("message", "You successfully uploaded ");
} catch (IOException e) {
e.printStackTrace();
}
return "upload_result";
}
}
4、前端页面代码
上传页面
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Spring Boot file upload example</h1>
<!-- 上传单个对象 注意表单的method属性设为post,enctype属性设为multipart/form-data -->
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" /><br/><br/>
<input type="submit" value="上传" />
</form>
<!-- 上传多个对象 注意表单的method属性设为post,enctype属性设为multipart/form-data -->
<form method="POST" action="/uploadMultiFiles" enctype="multipart/form-data">
<p>文件1:<input type="file" name="file" /></p>
<p>文件2:<input type="file" name="file" /></p>
<p>文件3:<input type="file" name="file" /></p>
<!-- 同时传递其他业务字段 -->
<p>用户名:<input type="text" name="userName" /></p>
<p>年龄:<input type="text" name="age" /></p>
<p><input type="submit" value="上传" /></p>
</form>
</body>
</html>
结果页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>上传结果为:${message}</h2>
<img alt="图片不能显示" src="/myres/QQ图片20190222180514.png"/>
</body>
</html>
注:图片显示需要配置相关映射
<Context docBase="f:/myres" path="/myres"/>
意思就是当访问相对路径path时,就会自动自动访问dobase路径下的文件
具体设置参见:https://blog.csdn.net/Sunmeok/article/details/81477585
转载于:https://www.cnblogs.com/jeat/p/10431880.html