1. Create a page called upload.html under static directory
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" value="选择文件" name="uploadFile">
<input type="submit" value="上传文件">
</form>
</body>
</html>
2. Create a file upload interfaces:
package com.example.demo.Controllers;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@RestController
public class FileUploadController {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/"); //实例化时间格式的对象
@PostMapping("/upload") //post方法访问upload目录
//创建请求对象与文件操作对象
public String upload(MultipartFile uploadFile, HttpServletRequest req){
//记录文件上传路径
String relPath =req.getSession().getServletContext().getRealPath("/uploadFile/");
//当前日期格式化
String format = sdf.format(new Date());
File folder = new File(relPath+format); //初始化文件对象设置记录的目录与时间
if(!folder.isDirectory()){ //判断是否为目录
folder.mkdirs(); //否则创建目录
}
String oldName = uploadFile.getOriginalFilename(); //获取上传文件的文件名
String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
try{
uploadFile.transferTo(new File(folder, newName));
//将当前ip+端口+目录+格式+文件名称进行拼接
String filePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/uploadFile/" + format + newName;
return filePath; //在页面上返回文件路径
}catch (IOException e){
e.printStackTrace();
}
return "上传失败!";
}
}
3. Run the program:
Select a file is good, not too much attention
, Then click Upload:
Input can be found:
File size exception handling is used in the springboot @ControllerAdvice globally exception handling, combined with @ExceptionHandler define a global exception trapping mechanism, if the uploaded file is too large, it will capture an IOException.
Definition of a class called ExceptionHandler, the model returns a view object:
@ControllerAdvice
public class ExceptionHandler {
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ModelAndView uploadException(MaxUploadSizeExceededException e)throws IOException{
ModelAndView mv = new ModelAndView();
mv.addObject("msg","上传文件大小超过限制");
mv.setViewName("error");
return mv;
}
}
Then create a page called error.html in the templates directory:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Error</title>
</head>
<body>
<div th:text="${msg}"></div>
</body>
</html>
Upload a large file, the page returns the following results: