本文将阐述使用fastdfs客户端插件去访问fastdfs服务。

  • idea2018.1.5
  • jdk-8u162-windows-x64
  • 已经安装fastdfs服务,作者的图片服务器ip为 192.168.100.192,请读者根据自己的实际情况修改ip,storaged端口一般为22122

官网:
https://github.com/happyfish100/fastdfs-client-java
百度网盘:
链接:https://pan.baidu.com/s/1CeQ6CWg7tlJy9MalF8NCeg
提取码:ptco

以下为项目结构:
项目结构

源码中已经有配置,我们简化处理,修改fdfs_client.conf为以下内容:

  1. tracker_server=192.168.100.192:22122

在src/java中新建TestUpload.java

  1. import org.csource.common.MyException;
  2. import org.csource.fastdfs.*;
  3. import java.io.IOException;
  4. public class Test {
  5. public static void main(String[] args) throws IOException, MyException {
  6. //1、加载配置文件
  7. ClientGlobal.init("fdfs_client.conf");
  8. //2、创建一个TrackerClient对象。
  9. TrackerClient trackerClient = new TrackerClient();
  10. //3、使用TrackerClient对象获得trackerserver对象。
  11. TrackerServer trackerServer = trackerClient.getConnection();
  12. //4、创建一个StorageClient对象。trackerserver、StorageServer两个参数。
  13. StorageClient storageClient = new StorageClient(trackerServer, null);
  14. //5、使用StorageClient对象上传文件。
  15. String[] strings = storageClient.upload_file("1.png", "png", null);
  16. //返回的数组包含两个元素分别类似于:group1、M00/00/00/wKhkwFyuYo6Aawy0AAH4I7umxyo333.png
  17. for (String string : strings) {
  18. System.out.println(string);
  19. }
  20. }
  21. }

在src/java中创建TestDownload.java

  1. import org.csource.common.MyException;
  2. import org.csource.fastdfs.ClientGlobal;
  3. import org.csource.fastdfs.StorageClient;
  4. import org.csource.fastdfs.TrackerClient;
  5. import org.csource.fastdfs.TrackerServer;
  6. import java.io.IOException;
  7. public class TestDownload {
  8. public static void main(String[] args) throws IOException, MyException {
  9. //1、加载配置文件
  10. ClientGlobal.init("fdfs_client.conf");
  11. //2、创建一个TrackerClient对象。
  12. TrackerClient trackerClient = new TrackerClient();
  13. //3、使用TrackerClient对象获得trackerserver对象。
  14. TrackerServer trackerServer = trackerClient.getConnection();
  15. //4、创建一个StorageClient对象。trackerserver、StorageServer两个参数。
  16. StorageClient storageClient = new StorageClient(trackerServer, null);
  17. //5、使用StorageClient对象下载文件。
  18. storageClient.download_file("group1", "M00/00/00/wKhkwFyuZo-AHPJEAAH4I7umxyo675.png", "2.png");
  19. }
  20. }

至此,我们使用fastdfs-client完成了文件的上传和下载。不过要注意的是,在实际使用过程中,我们自己的项目用的是该开源项目生成的jar包,并非直接使用该源代码。

版权声明:本文为alichengxuyuan原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/alichengxuyuan/p/12581330.html