创建SpringBoot项目
Maven依赖
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-thymeleaf
com.fasterxml.jackson.core
jackson-databind
application.yml
spring:
#前缀,也就是模板存放的路径
thymeleaf:
prefix: classpath:/templates/
#编码格式
encoding: UTF-8
#关闭缓存,不然无法看到实时页面
cache: false
#后缀
suffix: .html
#设置不严格的html
mode: HTML
servlet:
content-type: text/html
单文件上传
前台页面
Insert title here
文件上传
选择文件:
后台Controller
@Controller
public class FileUploadController {
/**
* 实现单文件上传
*/
@PostMapping("/fileUpload")
@ResponseBody
public String fileUpload(@RequestParam("fileName") MultipartFile file) {
if (file.isEmpty()) {
return "false";
}
String fileName = file.getOriginalFilename();
int size = (int) file.getSize();
System.out.println(fileName + "-->" + size);
String path = "E:/test";
File dest = new File(path + "/" + fileName);
if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest); //保存文件
return "true";
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
return "false";
}
}
}
多文件上传
前台页面
Insert title here
文件上传
选择文件1:
选择文件2:
选择文件3:
后台Controller
@Controller
public class FileUploadController {
/**
* 实现多文件上传
*/
@PostMapping(value = "/multifileUpload")
@ResponseBody
public String multifileUpload(HttpServletRequest request) {
List files = ((MultipartHttpServletRequest) request).getFiles("fileName");
if (files.isEmpty()) {
return "false";
}
String path = "E:/test";
for (MultipartFile file : files) {
String fileName = file.getOriginalFilename();
int size = (int) file.getSize();
System.out.println(fileName + "-->" + size);
if (file.isEmpty()) {
return "false";
}
File dest = new File(path + "/" + fileName);
if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest);
} catch (Exception e) {
e.printStackTrace();
return "false";
}
}
return "true";
}
}