基于FastDFS实现分布式存储的上传下载等操作
基于FastDFS实现分布式存储的上传下载等操作
标签:FastDFS Java
基于FastDFS实现分布式存储的上传下载等操作,并将程序封装成工具类方便直接使用。有需要源码的同学可私信。整体项目实现分解成下文5个步骤。
1、在项目中添加依赖到Maven的pom文件
org.csource fastdfs-client-java 1.27-SNAPSHOT commons-io commons-io 2.42、FastDFS客户端工具类,已封装如下(方便直接使用,有需要源码的同学可私信):
主要工具类方法:
/**
-
@Description 文件存储上传客户端
-
@author [email protected]
-
@time 2020年5月30日 上午9:27:26
/
public class FastDFSClient {
/*- MultipartFile 上传文件
- @param file MultipartFile
- @return 返回上传成功后的文件路径
*/
public static String uploadFileWithMultipart(MultipartFile file) throws BusinessException {
return upload(file, null);
}
/**
- 以附件形式下载文件
- @param filepath 文件路径
- @param response
*/
public static void downloadFile(String filepath, HttpServletResponse response) throws BusinessException {
download(filepath, null, null, response);
}
/**
-
删除文件
-
@param filepath 文件路径
-
@return 删除成功返回 0, 失败返回其它
*/
public static int deleteFile(String filepath) throws BusinessException {
if (StringUtils.isBlank(filepath)) {
throw new BusinessException(FileErrorCode.FILE_PATH_ISNULL.CODE);
}TrackerServer trackerServer = TrackerServerPool.borrowObject();
StorageClient1 storageClient = new StorageClient1(trackerServer, null);
int success = 0;
try {
success = storageClient.delete_file1(filepath);
if (success != 0) {
throw new BusinessException(FileErrorCode.FILE_DELETE_FAILED.CODE);
}
} catch (IOException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
throw new BusinessException(FileErrorCode.FILE_DELETE_FAILED.CODE);
}
// 返还对象
TrackerServerPool.returnObject(trackerServer);
return success;
}
}
3、将fastdfs-client.properties配置文件放置于引用项目的resource目录下
4、如下图,在项目中可直接通过FastDFSClient工具类调用所用的方法
5、项目中上传文件后使用的效果,由前端页面上传文件,至此项目实现分布式存储。