1. 程式人生 > >ubntu下單機配置fastdfs作為開發環境(4)---將 fastdfs客戶端整合到現有java專案中

ubntu下單機配置fastdfs作為開發環境(4)---將 fastdfs客戶端整合到現有java專案中

前言

話說,起初還覺得fastdfs的配置及整合會很簡單。。結果不是的。單單篇幅已經有四篇文章了。

正題:
請參考:

關於FastDFS蛋疼的叢集和負載均衡(九)之建立FastDFS的Maven專案

這一系列文章有意思。

FastDFS java client SDK

在這裡插入圖片描述

注意。。。

<dependency>
    <groupId>org.csource</groupId>
    <artifactId>fastdfs-client-java</artifactId>
    <version>1.27-SNAPSHOT</version>
</dependency>

這個是沒辦法用的,因為,我在gradle上面是broken path,找不到這玩意。。

在這裡插入圖片描述

在這裡插入圖片描述

在這裡插入圖片描述

好了,下面這個連結能綁到我們:
FastDFS Client Java » 1.27-RELEASE

<!-- https://mvnrepository.com/artifact/cn.bestwu/fastdfs-client-java -->
<dependency>
    <groupId>cn.bestwu</groupId>
    <artifactId>fastdfs-client-java</artifactId>
    <version>1.27</version>
</dependency>


這是從fork出來的jar拿過來的。

在這裡插入圖片描述

在這裡插入圖片描述

起碼能用了。

fastDFS與Java整合上傳下載

整合過程

1、採用了properties檔案作為配置檔案

在這裡插入圖片描述

fastdfs.connect_timeout_in_seconds = 5
fastdfs.network_timeout_in_seconds = 30
fastdfs.charset = UTF-8
fastdfs.http_anti_steal_token = false
fastdfs.http_secret_key = FastDFS1234567890
fastdfs.http_tracker_http_port = 80
#fastdfs.tracker_servers = tw-server:22122,10.0.11.202:22122,10.0.11.203:22122
fastdfs.tracker_servers = tw-server:22122

其他檔案:

package net.w2p.DevBase.plugins;

import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.URL;
import java.util.Properties;

import org.apache.commons.io.FilenameUtils;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

/**
 * @ClassName FastDFSUtils
 * @Description FastDFS工具類
 * @author zhangkai
 * @date 2017年7月18日
 */
public class FastDFSPlugin implements Serializable{
    /**
     *
     */
    private static final long serialVersionUID = -4462272673174266738L;
    private static TrackerClient trackerClient;
    private static TrackerServer trackerServer;
    private static StorageClient1 storageClient1;
    private static Properties config;

    static {
        config=new Properties();
        InputStream inputStream=null;
        try{
            InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("conf/fdfs_client.properties");
            InputStreamReader is=new InputStreamReader(in,"utf-8");
            config.load(is);
            is.close();
            in.close();
        }
        catch (Exception ed){
            ed.printStackTrace();
        }
        try {
//            ClientGlobal.init(resource.getClassLoader().getResource("conf/fdfs_client.conf").getPath());
            //-_- 沒辦法,原本的框架是web,app兩用的,沒辦法簡單粗暴用一個file path來指定檔案路徑的。

            ClientGlobal.initByProperties(config);
            //trackerclient
            trackerClient = new TrackerClient();
            trackerServer = trackerClient.getConnection();
            //storageclient
            storageClient1 = new StorageClient1(trackerServer,null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * fastDFS檔案上傳
     * @param file 上傳的檔案 FastDFSFile
     * @return String 返回檔案的絕對路徑
     */
    public static String uploadFile(FastDFSFile file){
        String path = null;
        try {
            //副檔名
            String ext = FilenameUtils.getExtension(file.getName());
            //mata list是表文件的描述
            NameValuePair[] mata_list = new NameValuePair[3];
            mata_list[0] = new NameValuePair("fileName",file.getName());
            mata_list[1] = new NameValuePair("fileExt",ext);
            mata_list[2] = new NameValuePair("fileSize",String.valueOf(file.getSize()));
            path = storageClient1.upload_file1(file.getContent(), ext, mata_list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }

    /**
     * fastDFS檔案下載
     * @param groupName 組名
     * @param remoteFileName 檔名
     * @param specFileName 真實檔名
     * @return ResponseEntity<byte[]>
     */
    public static ResponseEntity<byte[]> downloadFile(String groupName, String remoteFileName, String specFileName){
        byte[] content = null;
        HttpHeaders headers = new HttpHeaders();
        try {
            content = storageClient1.download_file(groupName, remoteFileName);
            headers.setContentDispositionFormData("attachment",  new String(specFileName.getBytes("UTF-8"),"iso-8859-1"));
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity<byte[]>(content, headers, HttpStatus.CREATED);
    }

    /**
     * 根據fastDFS返回的path得到檔案的組名
     * @param path fastDFS返回的path
     * @return
     */
    public static String getGroupFormFilePath(String path){
        return path.split("/")[0];
    }

    /**
     * 根據fastDFS返回的path得到檔名
     * @param path fastDFS返回的path
     * @return
     */
    public static String getFileNameFormFilePath(String path) {
        return path.substring(path.indexOf("/")+1);
    }
}

package net.w2p.DevBase.plugins;

import java.io.Serializable;
import java.util.Arrays;

/**
 * @ClassName FastDFSFile
 * @Description FastDFS上傳檔案業務物件
 * @author zhangkai
 * @date 2017年7月18日
 */
public class FastDFSFile implements Serializable{

    private static final long serialVersionUID = 2637755431406080379L;
    /**
     * 檔案二進位制
     */
    private byte[] content;
    /**
     * 檔名稱
     */
    private String name;
    /**
     * 檔案長度
     */
    private Long size;

    public FastDFSFile(){

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

    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 Long getSize() {
        return size;
    }
    public void setSize(Long size) {
        this.size = size;
    }
    public static long getSerialversionuid() {
        return serialVersionUID;
    }
}

測試用檔案:

package others;

import main.BaseTest;
import net.w2p.DevBase.plugins.FastDFSFile;
import net.w2p.DevBase.plugins.FastDFSPlugin;
import net.w2p.Shared.common.FileReadUtil;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

import java.io.*;

public class FastDfSTester extends BaseTest {
    private byte[] toByteArray(InputStream in) throws IOException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }

    @Test
    public void test_upload(){
        String encoding = "UTF-8";
        String fileName="/home/2.jpg";
        File file = new File(fileName);
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        try {
            FileInputStream in = new FileInputStream(file);
            byte[] content=toByteArray(in);
            in.close();
            FastDFSFile fastDFSFile = new FastDFSFile(content, file.getName(), filelength);
            String path = FastDFSPlugin.uploadFile(fastDFSFile);
            System.out.println(path);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}

測試結果:
在這裡插入圖片描述

在這裡插入圖片描述

done。