使用fastdfs-client-java對fastdfs進行操作

項目整體

maven

   <dependency>
      <groupId>net.oschina.zcx7878</groupId>
      <artifactId>fastdfs-client-java</artifactId>
      <version>1.27.0.0</version>
    </dependency>

這里把文件上傳的相關屬性封裝在了一個接口中,需要用到文件上傳的相關實體或者工具類直接實現這個接口即可:

public interface FileManagerConfig extends Serializable {

    public static final String FILE_DEFAULT_AUTHOR = "WangLiang";

    public static final String PROTOCOL = "http://";

    public static final String SEPARATOR = "/";

    public static final String TRACKER_NGNIX_ADDR = "192.168.0.68";

    public static final String TRACKER_NGNIX_PORT = "";

    public static final String CLIENT_CONFIG_FILE = "fdfs_client.conf";
}

接下來定義FastDFS文件的實體類:

package com.wl.bean;

/**
 * <strong>類概要: FastDFS文件實體</strong> <br>
 * <strong>創建時間: 2016-9-27 下午10:29:25</strong> <br>
 * 
 * @Project springmvc-main(com.wl.bean)
 * @author Wang Liang
 * @version 1.0.0
 */
public class FastDFSFile implements FileManagerConfig {

    private static final long serialVersionUID = 1L;

    private byte[] content;
    private String name;
    private String ext;
    private String length;
    private String author = FILE_DEFAULT_AUTHOR;

    public FastDFSFile(byte[] content, String ext) {
        this.content = content;
        this.ext = ext;
    }

    public FastDFSFile(byte[] content, String name, String ext) {
        this.content = content;
        this.name = name;
        this.ext = ext;
    }

    public FastDFSFile(byte[] content, String name, String ext, String length,
            String author) {
        this.content = content;
        this.name = name;
        this.ext = ext;
        this.length = length;
        this.author = author;
    }

    public byte[] getContent() {
        return content;
    }

    public void setContent(byte[] content) {
        this.content = content;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getExt() {
        return ext;
    }

    public void setExt(String ext) {
        this.ext = ext;
    }

    public String getLength() {
        return length;
    }

    public void setLength(String length) {
        this.length = length;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

}

如上所示,包括上傳所必須的file_buff和file_ext_name以及在meta_list中存放的幾個文件描述屬性。接下來看一下核心工具類FileManager:

import java.io.File;
import java.io.IOException;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

/**
 * <strong>類概要: FastDFS Java客戶端工具類</strong> <br>
 * <strong>創建時間: 2016-9-26 上午10:26:48</strong> <br>
 * 
 * @Project springmvc-main(com.wl.bean)
 * @author Wang Liang
 * @version 1.0.0
 */
public class FileManager implements FileManagerConfig {

    private static final long serialVersionUID = 1L;
    private static TrackerClient trackerClient;
    private static TrackerServer trackerServer;
    private static StorageServer storageServer;
    private static StorageClient storageClient;

    static {
        try {
            String classPath = new File(FileManager.class.getResource("/").getFile()).getCanonicalPath();

            String fdfsClientConfigFilePath = classPath + File.separator + CLIENT_CONFIG_FILE;
            ClientGlobal.init(fdfsClientConfigFilePath);

            trackerClient = new TrackerClient();
            trackerServer = trackerClient.getConnection();

            storageClient = new StorageClient(trackerServer, storageServer);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * <strong>方法概要: 文件上傳</strong> <br>
     * <strong>創建時間: 2016-9-26 上午10:26:11</strong> <br>
     * 
     * @param FastDFSFile
     *            file
     * @return fileAbsolutePath
     * @author Wang Liang
     */
    public static String upload(FastDFSFile file,NameValuePair[] valuePairs) {
        String[] uploadResults = null;
        try {
            uploadResults = storageClient.upload_file(file.getContent(),file.getExt(), valuePairs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String groupName = uploadResults[0];
        String remoteFileName = uploadResults[1];

        String fileAbsolutePath = PROTOCOL
                + TRACKER_NGNIX_ADDR
                //+ trackerServer.getInetSocketAddress().getHostName()
                //+ SEPARATOR + TRACKER_NGNIX_PORT 
                + SEPARATOR + groupName
                + SEPARATOR + remoteFileName;
        return fileAbsolutePath;
    }
}

如上所示,在類初始化時加載fdfs_client.conf配置文件并構造tracker server和storage server,文件上傳是通過storageClient.upload_file方法來實現的,而返回的uploadResults字符串數組正是文件名,固定兩個元素,uploadResults[0]是組名(group),而uploadResults[1]就是組名后面的文件全名了,最后我們的方法中有做了部分拼接使得FileManager.upload直接可以返回完成的文件路徑,下面就是我們調用上傳方法了:

package com.neuedu;

import org.csource.common.NameValuePair;

import java.io.FileInputStream;
import java.io.IOException;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args ) throws IOException {
        // 獲取文件后綴名
        String ext = "jpg";
        FileInputStream fileReader = new FileInputStream("d:/dog.jpg");
        byte[] bytes = new byte[10000000];//10M
        int length = fileReader.read(bytes);
        FastDFSFile file = new FastDFSFile(bytes,ext);
        NameValuePair[] meta_list = new NameValuePair[4];
        meta_list[0] = new NameValuePair("fileName", "abc");
        meta_list[1] = new NameValuePair("fileLength", String.valueOf(length));
        meta_list[2] = new NameValuePair("fileExt", ext);
        meta_list[3] = new NameValuePair("fileAuthor", "WangLiang");
        String filePath = FileManager.upload(file,meta_list);
        System.out.println(filePath);
    }
}

fdfs_client.conf

connect_timeout = 2

network_timeout = 30

charset = UTF-8

http.tracker_http_port = 80

http.anti_steal_token = no

http.secret_key = FastDFS1234567890

tracker_server = 192.168.238.130:22122
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,933評論 18 139
  • FastDFS是用C語言編寫的一款開源的輕量級分布式文件系統。它對文件進行管理,功能包括:文件存儲、文件同步、文件...
    歡醉閱讀 4,063評論 3 12
  • 上傳模塊配置樣例: # 上傳大小限制(包括所有內容) client_max_body_size 100m; # 上...
    SkTj閱讀 13,169評論 0 3
  • 概念: FastDFS是余慶(前阿里巴巴架構師,現易到用車架構師)開發的一個開源的輕量級分布式文件系統,對于小文件...
    yingyingguigui閱讀 5,853評論 0 2