1.首先我们使用正常的模板引擎thymeleaf去进行页面渲染,添加正常的一些依赖
<!-- thymeleaf模板 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.现在我们的视图默认会到resources/templates去寻找我们的试图,我们新建html页面uploadFile.html,
<html>
<head>
<title>Title</title>
</head>
<body>
单个文件上传:<br/>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="提交上传"/>
</form>
<br/>
多个文件上传:
<form action="/uploads" method="post" enctype="multipart/form-data">
文件1:<input type="file" name="file"/><br/>
文件2:<input type="file" name="file"/><br/>
文件3:<input type="file" name="file"/><br/>
<input type="submit" value="上传多个文件"/>
</form>
</body>
</html>
3.新建控制层UploadController.class,上传图片方法
/**
* 初始化上传文件界面,跳转到uploadFile.html
* @return
*/
@RequestMapping(value = "/upload",method = RequestMethod.GET)
public String index2(){
return "uploadFile";
}
/**
* 提取上传方法为公共方法
* @param uploadDir 上传文件目录
* @param file 上传对象
* @throws Exception
*/
private void executeUpload(String uploadDir,MultipartFile file) throws Exception
{
//文件后缀名
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//上传文件名
String filename = UUID.randomUUID() + suffix;
//服务器端保存的文件对象
File serverFile = new File(uploadDir + filename);
//将上传的文件写入到服务器端文件内
file.transferTo(serverFile);
}
/**
* 上传文件方法
* @param file 前台上传的文件对象
* @return
*/
@RequestMapping(value = "/upload",method = RequestMethod.POST)
public @ResponseBody
String upload(HttpServletRequest request, MultipartFile file)
{
try {
//上传目录地址
String uploadDir = request.getSession().getServletContext().getRealPath("/") +"upload/";
//如果目录不存在,自动创建文件夹
File dir = new File(uploadDir);
if(!dir.exists())
{
dir.mkdir();
}
//调用上传方法
executeUpload(uploadDir,file);
}catch (Exception e)
{
//打印错误堆栈信息
e.printStackTrace();
return "上传失败";
}
return "上传成功";
}
/**
* 上传多个文件
* @param request 请求对象
* @param file 上传文件集合
* @return
*/
@RequestMapping(value = "/uploads",method = RequestMethod.POST)
public @ResponseBody
String uploads(HttpServletRequest request, MultipartFile[] file)
{
try {
//上传目录地址
String uploadDir = request.getSession().getServletContext().getRealPath("/") +"upload/";
//如果目录不存在,自动创建文件夹
File dir = new File(uploadDir);
if(!dir.exists())
{
dir.mkdir();
}
//遍历文件数组执行上传
for (int i =0;i<file.length;i++) {
if(file[i] != null) {
//调用上传方法
executeUpload(uploadDir, file[i]);
}
}
}catch (Exception e)
{
//打印错误堆栈信息
e.printStackTrace();
return "上传失败";
}
return "上传成功";
}
我们运行项目,访问upload地址,会出现页面然后就可以上传了。
这里有一点需要注意,这个地方获取的地址是按照jsp的来,也就是说,我们需要在新建文件夹,webapp/WEB-INF/jsp,之后我们上传的文件会在webapp/WEB-INF/upload下可以看到
文章来源:https://www.jianshu.com/p/7903b6ebe47f