Java高級技術FastDFS的學習

1.定義 FastDFS 工具類

package an.cxy.util;

import org.csource.fastdfs.*;

public class ClientGlobalUtil {
    private static StorageClient storageClient;
    private static final String path = "fdfs.conf";
    static {
        try{
            ClientGlobal.init(path);
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);
            storageClient = new StorageClient(trackerServer,storeStorage);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static StorageClient getStorageClient(){
        return storageClient;
    }

   /* public static void main(String[] args) {
        System.out.println(getStorageClient());
    }*/
}

2.上傳文件測試

packagesinge;
import org.csource.common.NameValuePair; 
import org.csource.fastdfs.StorageClient; 
import org.junit.Test;
public class TestFileUpload{ 
    @Test 
    public void test() { 
        StringfileIds[] =testUpload("testFile", "1.jpg","jpg"); 
        if(fileIds==null){ 
            System.out.println("文件上傳失敗!"); 
        } 
        System.out.println(fileIds.length); 
        System.out.println("組名/卷名:"+ fileIds[0]); 
        System.out.println("路徑:"+fileIds[1]); 
    } 
    public String[] testUpload(StringdirName,StringfileName,StringfileType){ 
        StorageClientstorageClient=FastDFSClientUtils.getStorageClient(); 
        try{ // 要上傳的文件的元數據。可以自定義。 
            NameValuePairnvp[]=newNameValuePair[]{ 
                    newNameValuePair("filename",fileName) 
            };
/* * String[] upload_file(String fileName, String fileExtName, NameValuePair[]
metaList)
*fileName - 要上傳的本地文件,包含路徑地址。 * fileExtName - 文件後綴名;可以不傳遞,也就是傳遞一個 null。FastDFS 可以自動的在文件名中截取文件類型。 *metaList - 文件的描述元數據。 * 返回的結果是一個字符串數組。長度爲 2。0 位置是卷名-group1,1 位置是 文件名-M00/00/00/xxxxxx */ 
String fileIds[] =storageClient.upload_file(dirName+"/"+fileName,fileType,nvp);
        return fileIds; 
        }catch(Exceptione){ 
            e.printStackTrace(); 
        } 
        returnnull;
    }
}

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