页面代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/putpicture" method="post" enctype="multipart/form-data">
<input type="file" name="picture">
<input type="submit" value="上传图片">
</form>
</body>
</html>
注意,上传文件必须要把enctype="multipart/form-data"加上,不然无法上传
Controller
package com.example.academicadministration.controller;
import lombok.SneakyThrows;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.UUID;
@Controller
public class TestController {
@SneakyThrows
@RequestMapping("/putpicture")
public void PutPicture(MultipartFile picture){
//获取文件名
String filename= picture.getOriginalFilename();
//获取文件后缀
String suffixname=filename.substring(filename.lastIndexOf("."));
//生成随机文件名
filename= UUID.randomUUID()+suffixname;
String filepath="你想保存的路径";
//保存文件
picture.transferTo(new File(filepath+filename));
}
}
application.properties
spring.mvc.static-path-pattern=你自定义的虚拟访问路径
Photo=图片真实的绝对路径
spring.web.resources.static-locations=classpath:/static,classpath:/public,classpath:/resources,classpath:/META-INF/resources,file:${Photo}
spring.servlet.multipart.max-file-size=2MB 设置传输文件的最大容量
spring.webflux.multipart.headers-charset=UTF-8
mybatis.configuration.multiple-result-sets-enabled=true
标签:SpringBoot,spring,classpath,filename,虚拟,multipart,import,上传 From: https://www.cnblogs.com/liyiyang/p/17308173.html