FastDFS:使用Java代碼實現FastDFS上傳

1.創建項目

 

2.修改pom.xml

    <dependency>
      <groupId>net.oschina.zcx7878</groupId>
      <artifactId>fastdfs-client-java</artifactId>
      <version>1.27.0.0</version>
    </dependency>
    <!-- spring-core -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.3.25.RELEASE</version>
    </dependency>

 

3.創建fdfs_client.conf

connect_timeout=30

network_timeout=60

base_path=/home/fastdfs

#改爲自己服務器的ip
tracker_server=XXXXXXX: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

 

4.創建測試類進行文件上傳

package com.sxt;

import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args ) throws IOException, MyException {
        String uploadFilePath="C:/Users/LJH/Pictures/Camera Roll/timg.gif";

        String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
        System.out.println(filePath);
        // 1、加載配置文件,配置文件中的內容就是 tracker 服務的地址。
        ClientGlobal.init(filePath);
        // 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(uploadFilePath, "gif",
                null);
        // 7、返回數組。包含組名和圖片的路徑。
        for (String string : strings) {
            System.out.println(string);
        }
        System.out.println("上傳完成");
    }
}

 

5.測試

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章