文件( 上传与静态资源 ) 静态资源设置
配置文件
yaml
#application.yml
spring:
profiles:
active: devyaml
#application-dev.yml
# 文件存储路径
file:
path: E:\Blog\pic\
avatar: E:\Blog\avatar\
file: E:\Blog\file\
# 文件大小 /M
maxSize: 100
avatarMaxSize: 5yaml
#application-prod.yml
# 文件存储路径
file:
path: /user/****
avatar: /user/****
file: /user/****
# 文件大小 /M
maxSize: 100
avatarMaxSize: 5通过 http://localhost:8080/file/2022-05-09/xxx.jpg 如果设置了 context-path: /api 则 http://localhost:8080/api/file/2022-05-09/xxx.jpg
映射配置文件
java
@Configuration
@ConfigurationProperties(prefix = "file")
@Data
public class FileProperties {
private String path;
private String avatar;
private String file;
private String maxSize;
private String avatarMaxSize;
}配置类
java
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private FileProperties fileProperties;
/**
* 静态资源
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String avatarUtl = "file:" + fileProperties.getAvatar().replace("\\","/");
String pathUtl = "file:" + fileProperties.getPath().replace("\\","/");
String fileUtl = "file:" + fileProperties.getFile().replace("\\","/");
registry.addResourceHandler("/static/avatar/**").addResourceLocations(avatarUtl).setCachePeriod(0);
registry.addResourceHandler("/static/pic/**").addResourceLocations(pathUtl).setCachePeriod(0);
registry.addResourceHandler("/static/file/**").addResourceLocations(fileUtl).setCachePeriod(0);
/* 手动处理swagger */
registry.addResourceHandler("/swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
registry.addResourceHandler("/static/static/**")
.addResourceLocations("classpath:/META-INF/resources/").setCachePeriod(0);
}
}Springboot2 文件上传
单文件上传
先创建一个html表单
html
<el-upload
class="avatar-uploader"
action="https://jsonplaceholder.typicode.com/posts/"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>1.获取当前日期
(uploadDate):String
String uploadDate = new SimpleDateFormat("yyyy-mm-dd").format(new Date());
2.设置要保存到的目录
(savePath):String 绝对路径!!
项目运行时目录:
javaResponseEntity<ApiResult> upload(MultipartFile uploadFile, HttpServletRequest request){ String savePath = request.getSession().getServletContext().getRealPath("/upload/")+uploaddate; }指定存储目录
在配置文件设置好目录通过@Value("${a.aa.aaa}")读取
java@Value("${file.avater}") public String avaterPath; //头像存储目录 @Value("${file.file}") public String filePath; //文件存储目录 ResponseEntity<ApiResult> upload(MultipartFile uploadFile){ String savePath = avaterPath + "/" + uploaddate; }
3.如果目录不存在则创建
File folder = new File(savepath);
if (!folder.isDirectory()){folder.mkdirs();}
4.获取并修改文件名和类型
java
//原文件名 >>1.jpg 2.txt ...
String oldName = uploadFile.getOriginalFilename();
//原文件后缀 >>.jpg .png .txt ...
String nameType= oldName.substring(oldName.lastIndexOf("."));
//新文件名 >>a1-b2-c3.jpg
String newName = UUID.randomUUID().toString() + nameType;5.保存文件
java
try {
//保存并重命名 .transferTo(new File(路径,重命名))
uploadFile.transferTo(new File(folder,newName));
//获取保存后文件访问路径
String filePath = "/file/" + uploaddate + "/" + newName;
//返回上传成功后的文件名
return new ResponseEntity<>( ApiResult.ok(filePath),HttpStatus.OK);
}catch (IOException e){
return new ResponseEntity<>( ApiResult.failed("文件上传失败"),HttpStatus.FAILED_DEPENDENCY);
}完整代码
java
//application.yml
spring:
profiles:
active: devjava
//application-dev.yml
file:
avater: E:\shop\pcdev\file
file: E:\shop\linuxdev\filejava
@Value("${file.avater}")
String avaterPath;
@Value("${file.file}")
String filePath;
@PostMapping("/upload")
ResponseEntity<ApiResult> upload(MultipartFile uploadFile){
//获取当前日期 2022-5-9
String uploaddate = new SimpleDateFormat("yyyy-mm-dd").format(new Date());
//设置文件保存的文件夹路径
String savepath = avaterPath + "/" + uploaddate;
//创建文件夹,当文件夹不存在时
File folder = new File(savepath);
if (!folder.isDirectory()){folder.mkdirs();}
//旧文件名
String oldName = uploadFile.getOriginalFilename();
//文件后缀
String nameType= oldName.substring(oldName.lastIndexOf("."));
//新文件名
String newName = UUID.randomUUID().toString() + nameType;
try {
//保存并重命名
uploadFile.transferTo(new File(folder,newName));
//获取保存后文件访问路径
String filePath = "/file/" + uploaddate + "/" + newName;
return new ResponseEntity<>( ApiResult.ok(filePath),HttpStatus.OK);
}catch (IOException e){
return null;
}
}示例代码
java
@Value("${file.avater}")
String avaterPath;
@Value("${file.file}")
String filePath;
@PostMapping("/test")
ResponseEntity testResponseEntity(){
return new ResponseEntity<>(ApiResult.urlNotFoundMsg("东西没有"), HttpStatus.resolve(ApiResult.urlNotFoundMsg("").getStatus()));
}
@PostMapping("/upload")
ResponseEntity<ApiResult> upload(MultipartFile uploadFile){
//获取当前日期 2022-5-9
String uploaddate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//设置文件保存的文件夹路径
String savepath = avaterPath + "/" + uploaddate;
//创建文件夹,当文件夹不存在时
File folder = new File(savepath);
if (!folder.isDirectory()){folder.mkdirs();}
//旧文件名
String oldName = uploadFile.getOriginalFilename();
//文件后缀
String nameType= oldName.substring(oldName.lastIndexOf("."));
if (".jpg".equals(nameType) || ".png".equals(nameType) || ".gif".equals(nameType) || ".webp".equals(nameType) ||){
//新文件名
String newName = UUID.randomUUID().toString() + nameType;
try {
//保存并重命名
uploadFile.transferTo(new File(folder,newName));
//获取保存后文件访问路径
String filePath = "/file/" + uploaddate + "/" + newName;
return new ResponseEntity<>( ApiResult.ok(filePath),HttpStatus.OK);
}catch (IOException e){
return null;
}
}else {
return new ResponseEntity<>( ApiResult.failed("文件类型错误"),HttpStatus.FAILED_DEPENDENCY);
}
}
}