FastDFS 的作者余庆先生已经为我们开发好了 Java 对应的 SDK。这里需要解释一下:作者余庆并没有及时更新最新的 Java SDK 至 Maven 中央仓库,目前中央仓库最新版仍旧是 1.27 版。所以我们需要通过 Github:https://github.com/happyfish100/fastdfs-client-java 下载项目源码,再通过命令 mvn clean install 编译打包导入 Maven 仓库使用即可。
接下来我们通过 Java API 操作 FastDFS 实现文件的上传、下载、替换、删除、查询元数据、查询详情等功能。
文中案例已同步至:
Github:https://github.com/imrhelloworld/fastdfs-javaGitee:https://gitee.com/imrhelloworld/fastdfs-java
创建项目
添加依赖
在项目的 pom.xml 中添加以下依赖。因为我们需要一些常用工具包和单元测试,所以需要引入它们。
<dependency>
<groupId>org.csource
</groupId>
<artifactId>fastdfs-client-java
</artifactId>
<version>1.29-SNAPSHOT
</version>
</dependency>
<dependency>
<groupId>org.apache.commons
</groupId>
<artifactId>commons-lang3
</artifactId>
<version>3.11
</version>
</dependency>
<dependency>
<groupId>junit
</groupId>
<artifactId>junit
</artifactId>
<version>4.13
</version>
<scope>test
</scope>
</dependency>
编写配置文件
fdfs_client.conf
# 超时时间
connect_timeout = 10
network_timeout = 30
# 编码字符集
charset = UTF-8
# tracker 服务器 HTTP 协议下暴露的端口
http.tracker_http_port = 8080
# tracker 服务器的 IP 和端口
tracker_server = 192.168.10.101:22122
工具类
package org
.example
.client
;
import org
.apache
.commons
.lang3
.StringUtils
;
import org
.csource
.common
.MyException
;
import org
.csource
.common
.NameValuePair
;
import org
.csource
.fastdfs
.*
;
import java
.io
.*
;
public class FastDFSClient {
private static final String CONF_FILENAME
= Thread
.currentThread()
.getContextClassLoader().getResource("").getPath() + "fdfs_client.conf";
private static StorageClient storageClient
= null
;
static {
try {
ClientGlobal
.init(CONF_FILENAME
);
TrackerClient trackerClient
= new TrackerClient(ClientGlobal
.g_tracker_group
);
TrackerServer trackerServer
= trackerClient
.getTrackerServer();
StorageServer storageServer
= trackerClient
.getStoreStorage(trackerServer
);
storageClient
= new StorageClient(trackerServer
, storageServer
);
} catch (IOException e
) {
e
.printStackTrace();
} catch (MyException e
) {
e
.printStackTrace();
}
}
public static String
[] uploadFile(InputStream inputStream
, String fileName
) {
try {
byte[] fileBuff
= null
;
NameValuePair
[] metaList
= null
;
if (inputStream
!= null
) {
int len
= inputStream
.available();
metaList
= new NameValuePair[2];
metaList
[0] = new NameValuePair("file_name", fileName
);
metaList
[1] = new NameValuePair("file_length", String
.valueOf(len
));
fileBuff
= new byte[len
];
inputStream
.read(fileBuff
);
}
String
[] fileids
= storageClient
.upload_file(fileBuff
, getFileExt(fileName
), metaList
);
return fileids
;
} catch (IOException e
) {
e
.printStackTrace();
} catch (MyException e
) {
e
.printStackTrace();
}
return null
;
}
public static String
[] uploadFile(File file
, String fileName
) {
try (FileInputStream fis
= new FileInputStream(file
)) {
return uploadFile(fis
, fileName
);
} catch (FileNotFoundException e
) {
e
.printStackTrace();
} catch (IOException e
) {
e
.printStackTrace();
}
return null
;
}
private static String
getFileExt(String fileName
) {
if (StringUtils
.isBlank(fileName
) || !fileName
.contains(".")) {
return "";
}
return fileName
.substring(fileName
.lastIndexOf(".") + 1);
}
public static FileInfo
getFileInfo(String groupName
, String remoteFileName
) {
try {
return storageClient
.get_file_info(groupName
== null
? "group1" : groupName
, remoteFileName
);
} catch (IOException e
) {
e
.printStackTrace();
} catch (MyException e
) {
e
.printStackTrace();
}
return null
;
}
public static NameValuePair
[] getMetaData(String groupName
, String remoteFileName
) {
try {
return storageClient
.get_metadata(groupName
== null
? "group1" : groupName
, remoteFileName
);
} catch (IOException e
) {
e
.printStackTrace();
} catch (MyException e
) {
e
.printStackTrace();
}
return null
;
}
public static InputStream
downloadFile(String groupName
, String remoteFileName
) {
try {
byte[] bytes
= storageClient
.download_file(groupName
== null
? "group1" : groupName
, remoteFileName
);
InputStream inputStream
= new ByteArrayInputStream(bytes
);
return inputStream
;
} catch (IOException e
) {
e
.printStackTrace();
} catch (MyException e
) {
e
.printStackTrace();
}
return null
;
}
public static int deleteFile(String groupName
, String remoteFileName
) {
int result
= -1;
try {
result
= storageClient
.delete_file(groupName
== null
? "group1" : groupName
, remoteFileName
);
} catch (IOException e
) {
e
.printStackTrace();
} catch (MyException e
) {
e
.printStackTrace();
}
return result
;
}
public static String
[] modifyFile(String oldGroupName
, String oldFileName
, File file
, String fileName
) {
String
[] fileids
= uploadFile(file
, fileName
);
if (fileids
== null
) {
return null
;
}
int delResult
= deleteFile(oldGroupName
, oldFileName
);
if (delResult
!= 0) {
return null
;
}
return fileids
;
}
}
测试
文件上传
@Test
public void testUploadFile() {
String
[] fileids
= FastDFSClient
.uploadFile(new File("D:/china.jpg"), "china.jpg");
for (String fileid
: fileids
) {
System
.out
.println("fileid = " + fileid
);
}
}
返回值:
fileid
= group1
fileid
= M00/00/00/wKgKZl9xMdiAcOLdAADhaCZ_RF0096.jpg
文件详情
@Test
public void testGetFileInfo() {
FileInfo fileInfo
= FastDFSClient
.getFileInfo("group1", "M00/00/00/wKgKZl9xMdiAcOLdAADhaCZ_RF0096.jpg");
System
.out
.println("fileInfo = " + fileInfo
);
}
返回值:
fileInfo
= fetch_from_server
= false, file_type
= 1, source_ip_addr
= 192.168.10.102, file_size
= 57704, create_timestamp
= 2020-09-28 08:44:08, crc32
= 645874781
文件元数据
@Test
public void testGetMetaData() {
NameValuePair
[] metaDatas
= FastDFSClient
.getMetaData("group1", "M00/00/00/wKgKZl9xMdiAcOLdAADhaCZ_RF0096.jpg");
for (NameValuePair metaData
: metaDatas
) {
System
.out
.println(metaData
.getName() + "---" + metaData
.getValue());
}
}
返回值:
file_length---57704
file_name---china.jpg
文件下载
@Test
public void testDownloadFile() {
InputStream is
= FastDFSClient
.downloadFile("group1", "M00/00/00/wKgKZl9xMdiAcOLdAADhaCZ_RF0096.jpg");
try (FileOutputStream fos
= new FileOutputStream("D:/wKgKZl9xMdiAcOLdAADhaCZ_RF0096.jpg")) {
int len
= 0;
byte[] bytes
= new byte[1024];
while ((len
= is
.read(bytes
)) != -1) {
fos
.write(bytes
, 0, len
);
fos
.flush();
}
} catch (FileNotFoundException e
) {
e
.printStackTrace();
} catch (IOException e
) {
e
.printStackTrace();
}
}
文件删除
@Test
public void testDeleteFile() {
int result
= FastDFSClient
.deleteFile("group1", "M00/00/00/wKgKZl9xMdiAcOLdAADhaCZ_RF0096.jpg");
System
.out
.println("result = " + result
);
}
返回值:
result
= 0
文件替换
@Test
public void testModifyFile() {
String
[] fileids
= FastDFSClient
.modifyFile("group1", "M00/00/00/wKgKZl9xOS2ASdu8AADhaCZ_RF0898.jpg",
new File("D:/mhw.jpg"), "mhw.jpg");
for (String fileid
: fileids
) {
System
.out
.println("fileid = " + fileid
);
}
}
返回值:
fileid
= group1
fileid
= M00/00/00/wKgKZl9xOeaAFO00AACmo7QBGtA298.jpg
至此 Java 客户端操作 FastDFS 实现文件上传下载替换删除等操作就到这里,下一篇我们带大家搭建 FastDFS 的集群环境,多 Tracker 多 Storage 然后通过 Nginx 代理。
本文采用 知识共享「署名-非商业性使用-禁止演绎 4.0 国际」许可协议。
大家可以通过 分类 查看更多关于 FastDFS 的文章。
🤗 您的点赞和转发是对我最大的支持。
📢 关注公众号 哈喽沃德先生「文档 + 视频」每篇文章都配有专门视频讲解,学习更轻松噢 ~