用到了hutool工具类生成图片名
<!--hutool工具类 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.6</version>
</dependency>
yml 配置路径
spring:
servlet:
###多文件上传配置
multipart:
file-size-threshold: 100MB
max-file-size: 10MB
max-request-size: 100MB
#文件上传路径
#/home/yqs
#文件上传绝对路径(注意:结尾“/”)
#file.upload.imgPath=D://file/upload/=> /home/yqs/upload/
webapp:
data:
access-path: /upload/
path-pattern: ${webapp.data.access-path}/**
mapping-location-windows: D:/upload/
mapping-location-not-windows: /home/yqs/upload/
静态资源替换的配置
package com.yqs.config.file;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.File;
/**
*
* * @Description 本地资源配置
* * @Author 小乌龟
* * @Date 2022/2/22 9:08
*
* 作用: 用于配置静态资源映射的一些属性
* accessPath: 访问静态资源时的路径,如访问ip:port/visual/upload/xxx/xxx,其中visual是项目路径,upload便是accessPath
* mappingLocationWindows: 指明在windows下运行时accessPath映射到服务器磁盘的绝对路径,比如映射到D:/data
* mappingLocationNotWindows: 指明在Linux或Mac下运行时accessPath映射到服务器磁盘的绝对路径,比如映射到/usr/data
* pathPattern: 配置静态资源映射时的参数,表示路径匹配规则,如/upload/**表示以ip:port/visual/upload/开头的url
* 都会认为是访问静态资源,然后到mappingLocation指定的路径下去寻找资源
* resourceLocation: 配置静态资源映射时的参数,表示磁盘的绝对路径,如file:/usr/upload/,必须加上file。
*/
@Data
@Component
public class WebAppDataProperties {
@Value("${webapp.data.access-path}")
private String accessPath;
@Value("${webapp.data.path-pattern}")
private String pathPattern;
@Value("${webapp.data.mapping-location-windows}")
private String mappingLocationWindows;
@Value("${webapp.data.mapping-location-not-windows}")
private String mapperLocationNotWindows;
/**
*获取 文件存放路径(仅仅开头) 不存在就创建 判定服务器类型来摆放路径位置
* @return String
* @author zhangjunrong
* @date 2022/2/22 16:37
*/
public String getResourceLocation() {
String os = System.getProperty("os.name");
if (os.toLowerCase().startsWith("win")) {
File file = new File(mappingLocationWindows);
if (!file.exists()) {
file.mkdirs();
}
return "file:" + mappingLocationWindows;
} else {
File file = new File(mapperLocationNotWindows);
if (!file.exists()) {
file.mkdirs();
}
return "file:" + mapperLocationNotWindows;
}
}
/**
*主要通过这个来开头路径
* @param
* @return String 返回服务器的地址
* @author zhangjunrong
* @date 2022/2/24 10:30
*/
public String getMappingLocation() {
String os = System.getProperty("os.name");
return (os.toLowerCase().startsWith("win")) ? mappingLocationWindows : mapperLocationNotWindows;
}
}
package com.yqs.config.file;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @Description 自定义静态资源映射
* @Author 小乌龟
* @Date 2022/2/18 16:13
*/
@Configuration
public class FileUploadConfig implements WebMvcConfigurer {
@Autowired
private WebAppDataProperties webAppDataProperties;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(webAppDataProperties.getPathPattern())
.addResourceLocations(webAppDataProperties.getResourceLocation());
}
}
图片文件工具包 上传删除(其实只要把判定去了还要路径改一下 就是文件的上传和下载)
/**
* @Description 文件操作
* @Author 小乌龟
* @Date 2022/2/17 14:08
*/
@Slf4j
@Component
public class FileUtil {
/**工具类注入bean
* @author zhangjunrong
* @date 2022/2/22 19:30
*/
@Autowired
private WebAppDataProperties webAppDataProperties;
private static FileUtil fileUtil ;
@PostConstruct
public void init() {
fileUtil = this;
fileUtil.webAppDataProperties= this.webAppDataProperties;
}
/**
* 图片类型
*/
private static List<String> pictureTypes = new ArrayList<>();
static {
pictureTypes.add("jpg");
pictureTypes.add("jpeg");
pictureTypes.add("bmp");
pictureTypes.add("gif");
pictureTypes.add("png");
}
public static File getWebAppImagePath(String root,String filePath) {
String imageDir = root +"img/"+filePath;
File imageDirFile = getOrCreate(imageDir);
return imageDirFile;
}
private static File getOrCreate(String path) {
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
return file;
}
/**
* 判断是否是图片
*
* @param fileName
* @return
*/
public static Boolean isPicture(String fileName) {
if (StringUtils.isEmpty(fileName)) {
return false;
}
String expandName = getPicExpandedName(fileName);
return pictureTypes.contains(expandName);
}
/**
*下载图片 可判定是否是图片
* @param srcImage 图片文件
* @param filePath 图片路径 默认有 /home/yqs/upload/img/ 如填 article
* @return String img/xxx/xxx.png 如 img/article/123.png
* @author zhangjunrong
* @date 2022/2/22 21:48
*/
/**
*下载图片 可判定是否是图片
* @param srcImage 图片文件
* @param filePath 图片路径 默认有 /home/yqs/upload/img/ 如填 article
* @return String img/xxx/xxx.png 如 img/article/123.png
* @author zhangjunrong
* @date 2022/2/22 21:48
*/
public static String uploadImage(MultipartFile srcImage,String filePath) {
// 获取上传时的文件名
String imageName = srcImage.getOriginalFilename();
if(isPicture(imageName)) {
// 截取后缀
// String imageSuffix = imageName.substring(imageName.lastIndexOf("."));
// 图片的存储路径
File imagePath = getWebAppImagePath(fileUtil.webAppDataProperties.getMappingLocation(), filePath);
// 使用雪压算法作为保存时的文件名
String newImageName = IdUtil.getSnowflake(16).nextId() + ".jpg";
File destImage = new File(imagePath, newImageName);
try {
srcImage.transferTo(destImage);
//压缩图片 hutool仅支持jpg压缩
ImgUtil.compress(destImage,destImage,0.5f);
} catch (IOException e) {
e.printStackTrace();
}
StringBuilder imageUrl = new StringBuilder()
.append("img/")
.append(filePath)
.append("/")
.append(newImageName);
return imageUrl.toString();
}
return null;
}
/**
*图片删除 以提供路径 home/yqs/upload/ 需要 类型/文件名 如 img/article/1.png
* @param imgFilePath
* @return boolean
* @author zhangjunrong
* @date 2022/2/23 16:16
*/
public static boolean deleteImgFile(String imgFilePath){
return deleteFile(fileUtil.webAppDataProperties.getMappingLocation()+imgFilePath);
}
/**
* 删除单个文件
*
* @param fileName 要删除的文件的文件名
* @return 单个文件删除成功返回true,否则返回false
*/
public static boolean deleteFile(String fileName) {
File file = new File( fileName);
// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
if (file.exists() && file.isFile()) {
if (file.delete()) {
log.info("删除单个文件" + fileName + "成功!");
return true;
} else {
log.error("删除单个文件" + fileName + "失败!");
return false;
}
} else {
log.info("删除单个文件失败:" + fileName + "不存在!");
return false;
}
}
/**
* 获取后缀名 如果没有按jpg格式来
*
* @param fileName
* @return
*/
public static String getPicExpandedName(String fileName) {
String ext = "";
if (StringUtils.isNotBlank(fileName) &&
StringUtils.contains(fileName, ".")) {
ext = StringUtils.substring(fileName, fileName.lastIndexOf(".") + 1);
}
ext = ext.toLowerCase();
if (ext == null || ext.length() < 1) {
ext = "jpg";
}
return ext;
}
测试
文件上传:
文件删除: