一、fastdfs-client的jar包導入
1、下載地址:https://github.com/happyfish100/fastdfs-client-java
2、將代碼使用git下載下來之后,使用源碼安裝;
mvn clean install
3、安裝成功后,在項目的pom.xml文件中使用如下坐標引入;
<dependency> <groupId>org.csource</groupId> <artifactId>fastdfs-client-java</artifactId> <version>1.27-SNAPSHOT</version> </dependency>
二、配置fastdfs的配置文件
1、在引入的jar包中查找配置文件,下圖中的為例子(配置文件以.conf 或 .prpperties 結尾)
注:本帖子使用 .conf 作為配置文件;
2、在 classpath 路徑下創建 fdfs_client.conf 文件,並將上圖中的 fdfs_client.conf.sample文件內容拷貝到該文件中,修改配置文件中的 tracker_server 為指定的fastdfs主機的IP;
注1:tracker_server指向您自己IP地址和端口,1-n個 注2:除了tracker_server,其它配置項都是可選的
三、連接fastdfs分布式文件系統
FastDfsUtils.java
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.StorageServer; import org.csource.fastdfs.TrackerClient; import org.csource.fastdfs.TrackerServer; import org.springframework.core.io.ClassPathResource; /** * 連接fastdfs, 上傳圖片 * 返回上傳的路徑, 例如: group1/M00/00/00/wKisFFpBG9eAHaQvAAAWKd1hQR4158_big.jpg * @author pc * */ public class FastDfsUtils { //上傳圖片 public static String uploadPic(byte[] pic, String name, long size) throws Exception { //讀取配置文件 ClassPathResource resource = new ClassPathResource("fdfs_client.conf"); //從classpath路徑下讀取文件 ClientGlobal.init(resource.getClassLoader().getResource("fdfs_client.conf").getPath()); //連接tracker的客戶端 TrackerClient trackerClient = new TrackerClient(); TrackerServer trackerServer = trackerClient.getConnection(); //連接storage的客戶端 StorageServer storageServer = null; StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer); //上傳圖片 String ext = FilenameUtils.getExtension(name); //獲取擴展名 NameValuePair[] metaArr = new NameValuePair[3]; //描述信息 metaArr[0] = new NameValuePair("fileName", name); metaArr[1] = new NameValuePair("fileExt", ext); metaArr[2] = new NameValuePair("fileSize", String.valueOf(size)); String path = storageClient1.upload_file1(pic, ext, metaArr); //返回存儲的文件路徑 return path; } }
注:StorageClient1 為升級版本的, upload_file1(byte[], String, NameValuePair[]) 為升級版的方法;