【FastDFS】05 Java程序测试上传

创建普通Maven工程

 

导入所需依赖坐标:

    <dependencies>
        <!-- https://mvnrepository.com/artifact/net.oschina.zcx7878/fastdfs-client-java -->
        <dependency>
            <groupId>net.oschina.zcx7878</groupId>
            <artifactId>fastdfs-client-java</artifactId>
            <version>1.27.0.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
    </dependencies>

 

在Resource目录中编写FastDFS配置文件【fdfs_client.conf】

connect_timeout=30

network_timeout=60

base_path=/home/fastdfs

#改为自己服务器的ip
tracker_server=服务器或者虚拟IP地址:22122

log_level=info

use_connection_pool = false

connection_pool_max_idle_time = 3600

load_fdfs_parameters_from_tracker=false

use_storage_id = false

storage_ids_filename = storage_ids.conf

http.tracker_server_port=80

 

编写测试类:

    @Test
    public void testSample() throws Exception{
        // 上传的文件
        String filePath = "C:\\Users\\User-Dai\\Pictures\\Saved Pictures\\245099.jpg";

        // FastDFS上传需要的配置文件
        String configurationFilePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
        System.out.println(configurationFilePath);


        // 1、加载配置文件,配置文件中的内容就是 tracker 服务的地址。
        ClientGlobal.init(configurationFilePath);

        // 2、创建一个 TrackerClient 对象。直接 new 一个。
        TrackerClient trackerClient = new TrackerClient();

        // 3、使用 TrackerClient 对象创建连接,获得一个 TrackerServer 对象。
        TrackerServer trackerServer = trackerClient.getConnection();

        // 4、创建一个 StorageServer 的引用,值为 null
        StorageServer storageServer = null;

        // 5、创建一个 StorageClient 对象,需要两个参数 TrackerServer 对象、StorageServer 的引用
        StorageClient storageClient = new StorageClient(trackerServer, storageServer);
        // 6、使用 StorageClient 对象上传图片。
        //扩展名不带“.”
        String[] strings = storageClient.upload_file(filePath, "jpg", null);

        // 7、返回数组。包含组名和图片的路径。
        for (String string : strings) {
            System.out.println(string);
        }
        System.out.println("上传完成");
    }

测试结果:

C:\Users\User-Dai\IdeaProjects\FastDFS\target\classes\fdfs_client.conf
group1
M00/00/00/rBEAB180jHGAZ-ZDAAPzHYbtkp4809.jpg
上传完成

 

posted @ 2020-08-13 08:48  emdzz  阅读(190)  评论(0编辑  收藏  举报