上一篇文章,在服务器上安装了FastDFS
CentOS 安装FastDFS,配置Tracker和Storage服务
这一篇记录下在SpringBoot项目中添加使用FastDFS上传功能
1. pom文件添加依赖
<!-- https://mvnrepository.com/artifact/com.github.tobato/fastdfs-client -->
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.27.2</version>
</dependency>
复制代码
2. application添加FastDFS配置信息
fdfs:
# 连接超时时间
connect-timeout: 30
# 读取时间
so-timeout: 30
# tracker服务配置地址列表
tracker-list: 192.168.10.235:22122
复制代码
注意:tracker-list 填写的是 tracker 服务器的ip地址,不是 storage 服务器的ip
3. controller
@Autowired
public UploadService uploadService;
public String uploadFace(MultipartFile file) throws Exception {
// 获取上传文件的名称
String originalFilename = file.getOriginalFilename();
if (StringUtils.isBlank(originalFilename)) {
return "文件不能为空,请选择一个文件再上传!";
}
String[] fileNameArr = originalFilename.split("\\.");
// 文件后缀
String suffix = fileNameArr[fileNameArr.length - 1];
// 判断后缀是否符合
if (!suffix.equalsIgnoreCase("png")
&& !suffix.equalsIgnoreCase("jpg")
&& !suffix.equalsIgnoreCase("jpeg")) {
return "文件图片格式不支持!";
}
String filePath = uploadService.uploadFastDfs(file, suffix);
if (StringUtils.isBlank(filePath)) {
return "文件上传失败!";
}
return filePath;
}
复制代码
4. service
public interface UploadService {
/**
* 使用FastDFS上传文件
*
* @param file 要上传的文件
* @param fileExtName 文件扩展名
* @return 文件路径
* @throws IOException 文件上传异常
*/
public String uploadFastDfs(MultipartFile file, String fileExtName) throws IOException;
}
@Service
public class UploadServiceImpl implements UploadService {
@Autowired
public FastFileStorageClient fastFileStorageClient;
@Override
public String uploadFastDfs(MultipartFile file, String fileExtName) throws IOException {
StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(),
file.getSize(), fileExtName, null);
return storePath.getFullPath();
}
}
复制代码
近期评论