pom依赖
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.27.2</version>
</dependency>
yaml文件
# 分布式文件系统FDFS配置
fdfs:
so-timeout: 1500 # 读取时间
connect-timeout: 600 # 连接超时时间
thumb-image: #缩略图生成参数
width: 150
height: 150
tracker-list: #Tracker服务配置地址列表
- 192.168.3.10:22122
- 192.168.3.12:22122
- 192.168.3.13:22122
pool:
#从池中借出的对象的最大数目(配置为-1表示不限制)
max-total: -1
#获取连接时的最大等待毫秒数(默认配置为5秒)
max-wait-millis: 5000
#每个key最大连接数
max-total-per-key: 50
#每个key对应的连接池最大空闲连接数
max-idle-per-key: 10
#每个key对应的连接池最小空闲连接数
min-idle-per-key: 5
upload:
base-url: http://fastdfs.com:8888/
添加Config配置
@Configuration
public class FileConfig {
/**
* 解决上传文件过大导致异常的问题。
* the request was rejected because its size (170982031) exceeds the
configured
* @return
*/
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setMaxRequestSize(DataSize.ofBytes(200*1048576L));
factory.setMaxFileSize(DataSize.ofBytes(200*1048576L));
return factory.createMultipartConfig();
}
}
service层
@Autowired
private FastFileStorageClient fastFileStorageClient;
@Value("${upload.base-url}")
private String baseUrl;
/**
* 上传图片
* @param file
* @return
*/
public String uploadImage(MultipartFile file) {
try {
//校验文件
BufferedImage image = ImageIO.read(file.getInputStream());
if (image == null || image.getWidth() == 0 || image.getHeight() ==
0) {
throw new RuntimeException("上传文件不是图片");
}
} catch (IOException e) {
log.error("校验文件内容失败....{}", e);
throw new RuntimeException("校验文件内容失败" + e.getMessage());
}
try {
// 获取扩展名
String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
// String filename = UUID.randomUUID().toString();
// File baseUrlFile = new File(baseUrl);
// if (!baseUrlFile.exists()) baseUrlFile.mkdirs();
// File newfile = new File(baseUrlFile, filename+"."+extension);
// FileInputStream fileInputStream = new FileInputStream(newfile);
//上传略缩图
//StorePath storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(file.getInputStream(),
file.getSize(), extension, null);
// 上传到FastDFS
StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(),
extension, null);
// 返回路径
return baseUrl+storePath.getFullPath();
} catch (IOException e) {
log.error("【文件上传】上传文件失败!....{}", e);
throw new RuntimeException("【文件上传】上传文件失败!" +
e.getMessage());
}
}
文件下载
try {
byte[] bytes = fastFileStorageClient.downloadFile("group1",
"M00/00/00/wKgDDGDub22AO4HUAApS0I7eS2U644_150x150.jpg", new
DownloadByteArray());
FileOutputStream stream = new FileOutputStream("3_150x150.jpg");
stream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
文件删除
fastFileStorageClient.deleteFile("group1","M00/00/00/wKgDDGDub22AWGB_AApS0I7eS2
U026.jpg");