fastdfs java整合,Java 整合 FastDFS

Java 整合 FastDFS

整体逻辑

在页面上传文件后台由 MultipartFile 接收,接着将 MultipartFile 文件转发为 FastDFS 文件封装类 FastDFSFile,调用 FastDFSClient 类的封装方法,将文件(FastDFSFile)上传到 FastDFS 集群中,成功后集群中文件存储位置返回到页面。

依赖

org.csource

fastdfs-client-java

1.27-SNAPSHOT

FastDFS 配置

项目 resources 目录下添加fdfs_client.conf文件:

connect_timeout = 60 # 连接超时时间

network_timeout = 60 # 网络超时时间

charset = UTF-8 # 编码格式

http.tracker_http_port = 8080 #tracker 端口

http.anti_steal_token = no #token 防盗链功能

http.secret_key = 123456 #密钥

# tracer server 列表,多个 tracer server 的话,分行列出

tracker_server = 192.168.53.85:22122

tracker_server = 192.168.53.86:22122

实际使用时删除注释信息,否则会报错

封装 FastDFS 上传工具类

public class FastDFSFile {

private String name;

private byte[] content;

private String ext;

private String md5;

private String author;

//省略getter、setter

}

封装 FastDFSClient 工具类

public class FastDFSClient {

private static Logger logger = LoggerFactory.getLogger(FastDFSClient.class);

static {

try {

String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();

ClientGlobal.init(filePath);

} catch (Exception e) {

logger.error("FastDFS Client Init Fail!", e);

}

}

/**

* 文件上传

*

* @param file

* @return

*/

public static String[] upload(FastDFSFile file) {

logger.info("File Name: " + file.getName() + "File Length: " + file.getContent().length);

// 文件属性信息

NameValuePair[] meta_list = new NameValuePair[1];

meta_list[0] = new NameValuePair("author", file.getAuthor());

long startTime = System.currentTimeMillis();

String[] uploadResults = null;

StorageClient storageClient = null;

try {

storageClient = getStorageClient();

uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);

} catch (Exception e) {

logger.error("Non IO Exception when uploadind the file:" + file.getName(), e);

}

logger.info("upload_file time used:" + (System.currentTimeMillis() - startTime) + " ms");

// 验证上传结果

if (uploadResults == null && storageClient != null) {

logger.info("upload file fail, error code:" + storageClient.getErrorCode());

}

logger.info("upload file successfully!!!" + "group_name:" + uploadResults[0] + ", remoteFileName:" + " " + uploadResults[1]);

return uploadResults;

}

/**

* 获取 StorageClient

*

* @return

* @throws IOException

*/

public static StorageClient getStorageClient() throws IOException {

TrackerServer trackerServer = getTrackerServer();

StorageClient storageClient = new StorageClient(trackerServer, null);

return storageClient;

}

/**

* 获取 TrackerServer

*

* @return

* @throws IOException

*/

private static TrackerServer getTrackerServer() throws IOException {

TrackerClient trackerClient = new TrackerClient();

TrackerServer trackerServer = trackerClient.getConnection();

return trackerServer;

}

/**

* 根据 groupName 和文件名获取文件信息

*

* @param groupName

* @param remoteFileName

* @return

*/

public static FileInfo getFile(String groupName, String remoteFileName) {

try {

StorageClient storageClient = getStorageClient();

return storageClient.get_file_info(groupName, remoteFileName);

} catch (Exception e) {

logger.error("Non IO Exception: Get File from Fast DFS failed", e);

}

return null;

}

/**

* 根据 storageClient 的 API 获取文件的字节流并返回

*

* @param groupName

* @param remoteFileName

* @return

*/

public static InputStream downFile(String groupName, String remoteFileName) {

try {

StorageClient storageClient = getStorageClient();

byte[] bytes = storageClient.download_file(groupName, remoteFileName);

InputStream ins = new ByteArrayInputStream(bytes);

return ins;

} catch (Exception e) {

logger.error("Non IO Exception: Get File from Fast DFS failed", e);

}

return null;

}

/**

* 删除文件

*

* @param groupName

* @param remoteFileName

* @throws Exception

*/

public static void deleteFile(String groupName, String remoteFileName) throws Exception {

StorageClient storageClient = getStorageClient();

int i = storageClient.delete_file(groupName, remoteFileName);

logger.info("delete file successfully!!!" + i);

}

/**

* 生成文件地址

*

* @return

* @throws IOException

*/

public static String getTrackerUrl() throws IOException {

return "http://" + getTrackerServer().getInetSocketAddress().getHostString() + ":" + ClientGlobal.getG_tracker_http_port() + "/";

}

}

FastDFS 工具调用

@Controller

@RequestMapping("/fastdfs")

public class FastDFSController {

private static Logger logger = LoggerFactory.getLogger(FastDFSController.class);

/**

* 访问上传页面

*

* @return

*/

@GetMapping("/toUp")

public String toUp() {

return "fastdfs/toUp";

}

/**

* 上传文件

* @param file

* @param map

* @return

*/

@PostMapping("/singleFileUpload")

public String singleFileUpload(@RequestParam("file") MultipartFile file,

ModelMap map) {

if (file.isEmpty()) {

map.addAttribute("message", "Please select a file to upload");

return "/fastdfs/uploadStatus";

}

try {

String path=saveFile(file);

map.addAttribute("message",

"You successfully uploaded '" + file.getOriginalFilename() + "'");

map.addAttribute("path","file path url '" + path + "'");

} catch (Exception e) {

logger.error("upload file failed",e);

}

return "/fastdfs/uploadStatus";

}

/**

* 获取文件信息

* @param groupName: group1

* @param remoteFileName: M00/00/00/wKgBoF2kDXWAHdAKAAJsTdA9W_o579.png

* @return

*/

@PostMapping("/getFileInfo")

public String getFileInfo(String groupName, String remoteFileName){

FileInfo fileInfo = FastDFSClient.getFile(groupName, remoteFileName);

System.out.println("CRC32签名:" + fileInfo.getCrc32());

System.out.println("文件大小:" + fileInfo.getFileSize());

System.out.println("服务器地址:" + fileInfo.getSourceIpAddr());

System.out.println("创建时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(fileInfo.getCreateTimestamp()));

return "/fastdfs/uploadStatus";

}

/**

* 获取元数据信息

* @param groupName

* @param remoteFileName

* @return

* @throws Exception

*/

@PostMapping("/getMetaData")

public String getMetaData(String groupName, String remoteFileName)throws Exception{

NameValuePair[] get_metadata = FastDFSClient.getStorageClient().get_metadata(groupName,

remoteFileName);

for (NameValuePair nameValuePair: get_metadata) {

System.out.println("name: " + nameValuePair.getName() + " value: " + nameValuePair.getValue());

}

return "/fastdfs/uploadStatus";

}

/**

* 上传文件

*

* @param multipartFile

* @return

*/

private String saveFile(MultipartFile multipartFile) throws Exception {

String[] fileAbsolutePath = {};

String filename = multipartFile.getOriginalFilename();

String ext = filename.substring(filename.lastIndexOf(".") + 1);

byte[] file_buff = null;

InputStream inputStream = multipartFile.getInputStream();

if (inputStream != null) {

int lenl = inputStream.available();

file_buff = new byte[lenl];

inputStream.read(file_buff);

}

inputStream.close();

FastDFSFile file = new FastDFSFile(filename, file_buff, ext);

try {

fileAbsolutePath = FastDFSClient.upload(file);

} catch (Exception e) {

logger.error("upload file failed,please upload again!");

}

String path = FastDFSClient.getTrackerUrl() + fileAbsolutePath[0] + "/" + fileAbsolutePath[1];

return path;

}

}

解决Maven无法下载fastdfs-client-java依赖

# 下载 fastdfs-client-java 包

git clone https://github.com/happyfish100/fastdfs-client-java.git

# 进入下载好的fastdfs-client-java 解压

$ cd /fastdfs-client-java

# 使用maven打包jar

$ mvn clean install

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。
经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值