准备工作
yml配置
# DataSource Config
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3306/DataBaseName?useUnicode=true&useSSL=false&characterEncoding=utf8
servlet:
multipart:
enabled: true #是否启用http上传处理
max-request-size: 100MB #最大请求文件的大小
max-file-size: 20MB #设置单个文件最大长度
#file-size-threshold: 20MB #当文件达到多少时进行磁盘写入
mybatis-plus:
configuration:
map-underscore-to-camel-case: false # 数据库下划线自动转驼峰标示关闭
localhost: http://192.168.123.146:9090
swiperImage: ${localhost}/FTP/swiper/
FTP: ${localhost}/FTP/image/
ParcelImageAddress: ${localhost}/FTP/ParcelImage/
HeadImageAddress: ${localhost}/FTP/HeadImage/
SaveSwiperImageAddress: static/FTP/Swiper/
SaveParcelImageAddress: static/FTP/ParcelImage/
SaveHeadImageAddress: static/FTP/HeadImage/
其实要进行文件的本地的存储就是得在src下面的任何一个类里面就可以直接获取到resources里面的文件夹,那么你就可以进行操作了重点的代码如下:
String resources = SaveFile.class.getResource("/").getPath().toString();
//SaveFile这个是你保存文件的一个类
文件保存类的主类
package com.util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.UUID;
/**
* @author:DUOLUONIANDAI
* @DATA:2023/3/29 19:29
* @Title:文件进行保存操作
*/
@Repository
public class SaveFile {
@Value("${SaveParcelImageAddress}")
String parcelImageAddress;
@Value("${SaveHeadImageAddress}")
String headImageAddress;
@Value("${SaveSwiperImageAddress}")
String swiperImageAddress;
public boolean saveFilePlay(MultipartFile uploadFile, int play) {
try {
//
String resources = SaveFile.class.getResource("/").getPath().toString();
switch (play) {
case 1:
resources += swiperImageAddress;//保存swiper
break;
case 2:
resources += headImageAddress;//保存头像
break;
case 3:
resources += parcelImageAddress;//保存包裹图片
break;
default:{
return false;
}
}
//保证数据的文件夹存在
File file1 = new File(resources);
System.out.println(resources);
if(!file1.exists()){
file1.mkdirs();
}
//保存后后缀名
String originalFilename = uploadFile.getOriginalFilename();
originalFilename = originalFilename.substring(originalFilename.lastIndexOf('.'));
//生成id名
UUID uuid = UUID.randomUUID();
String name = uuid.toString() + originalFilename;
System.out.println(name);
//拼接路径
String tfile = resources + name;
System.out.println(tfile);
//获取文件流
InputStream inputStream = uploadFile.getInputStream();
file1 = new File(tfile);
//确保文件没有重复并创建容器
while (file1.exists()) {
uuid = UUID.randomUUID();
name = uuid.toString() + originalFilename;
System.out.println(name);
tfile = resources + name;
file1=new File(tfile);
}
file1.createNewFile();
//遍历写入所有的数据
FileOutputStream fileOutputStream = new FileOutputStream(file1);
byte[] bytes = new byte[1000000000];
int i;
while ((i = inputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, i);
}
inputStream.close();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}