1.依赖引入
<!--fastdfs依赖 -->
<dependency>
<groupId>net.oschina.zcx7878</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27.0.0</version>
</dependency>
<!-- 测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
2.配置文件编写
SpringBoot工程的resource包下创建fdfs_client.conf文件,编写
注:只需配置服务器地址tracker_server属性即可(端口号不变)
# connect timeout in seconds
# default value is 30s
connect_timeout = 2
# network timeout in seconds
# default value is 30s
network_timeout = 30
charSet = UTF-8
#HTTP settings
http.tracker_http_port = 80
http.anti_steal_token = no
http.secret_key = FastDFS1234567890
#重点:只要配置这项参数即可,192.168.223.140为文件服务器地址配置,22122为正常配置后的默认端口号,无需修改
tracker_server = 192.168.223.140:22122
3.工具类编写
1.static代码块:加载fastDFS的专有的配置文件
2.fdfsUpload:以输入流方式上传文件
3.fdfsUpload:以文件地址方式上传文件
4.fdfsDownload:下载文件到指定路径目录下,文件名默认为服务器下的文件名
5.fdfsDownload:下载文件,返回一个输出流
6.fdfsDeleteFile:删除服务器里面的指定文件
7.fdfdFileInfo:获取服务器文件信息
package com.hk.utils;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* @Author bigbeardhk
* @Date 2020/9/17 9:19
* @Email bigbeardhk@163.com
*/
public class FastDfsUtil {
private static TrackerClient trackerClient = null;
private static TrackerServer trackerServer = null;
private static StorageServer storageServer = null;
private static StorageClient storageClient = null;
static {
try {
//1.加载fastDFS的配置文件,用init()函数加载
ClientGlobal.init("fdfs_client.conf");
//2.构建管理者客户端
trackerClient = new TrackerClient();
//3.连接管理者服务端
trackerServer = trackerClient.getConnection();
//4.获取存储服务器的客户端对象
storageClient = new StorageClient(trackerServer, storageServer);
} catch (IOException | MyException e) {
throw new RuntimeException("FastDfs工具类初始化失败!");
}
}
/**
*
* @Title: fdfsUpload
* @Description: 通过文件流上传文件
* @param @param inputStream 文件流
* @param @param filename 文件名称,只用于获取文件后缀名
* @param @return
* @param @throws IOException
* @param @throws MyException
* @return String 返回文件在FastDfs的存储路径
* @throws
*/
public static String fdfsUpload(InputStream inputStream, String filename) throws IOException, MyException{
String suffix = "";
try{
if(filename.lastIndexOf(".")!=-1){
suffix = filename.substring(filename.lastIndexOf(".")+1);
}
}catch (Exception e) {
throw new RuntimeException("参数filename不正确!格式例如:a.png");
}
StringBuilder savepath = new StringBuilder();
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len = 0;
while ((len = inputStream.read(buff)) != -1) {
swapStream.write(buff, 0, len);
}
byte[] in2b = swapStream.toByteArray();
//上传文件
String[] strings = storageClient.upload_file(in2b, suffix, null);
for (String str : strings) {
savepath.append("/").append(str);
}
return savepath.toString();
}
/**
*
* @Title: fdfsUpload
* @Description: 本地文件上传
* @param @param filepath 本地文件路径
* @param @return
* @param @throws IOException
* @param @throws MyException
* @return String 返回文件在FastDfs的存储路径
* @throws
*/
public static String fdfsUpload(String filepath) throws IOException, MyException{
String suffix = "";
try{
if(filepath.lastIndexOf(".")!=-1){
suffix = filepath.substring(filepath.lastIndexOf(".")+1);
}
}catch (Exception e) {
throw new RuntimeException("上传的不是文件!");
}
StringBuilder savepath = new StringBuilder();
String[] strings = storageClient.upload_file(filepath, suffix, null);
for (String str : strings) {
savepath.append("/").append(str);
}
return savepath.toString();
}
/**
* @Title: fdfsDownload
* @Description: 下载文件到目录
* @param @param savepath 文件存储路径
* @param @param localPathDirectory 指定文件下载的父目录
* @param @return
* @param @throws IOException
* @param @throws MyException
* @return boolean 返回是否下载成功
* @throws
*/
public static boolean fdfsDownload(String savepath, String localPathDirectory) throws IOException, MyException{
//存储组
String group = "";
//存储路径
String path = "";
//指定文件下载的全路径
String localPath="";
try{
//第二个"/"索引位置
int secondindex = savepath.indexOf("/", 2);
//类似:group1
group = savepath.substring(1, secondindex);
//类似:M00/00/00/wKgBaFv9Ad-Abep_AAUtbU7xcws013.png
path = savepath.substring(secondindex + 1);
//文件下载后的名称,可自定义
int lastindex = savepath.lastIndexOf("/")+1;
String downLoadName=savepath.substring(lastindex);
localPath=localPathDirectory+"\"+downLoadName;
}catch (Exception e) {
throw new RuntimeException("传入文件存储路径不正确!格式例如:/group1/M00/00/00/wKgBaFv9Ad-Abep_AAUtbU7xcws013.png");
}
int result = storageClient.download_file(group, path, localPath);
if(result != 0){
throw new RuntimeException("下载文件失败:文件路径不对或者文件已删除!");
}
return true;
}
/**
* @Title: fdfsDownload
* @Description: 返回文件字符数组
* @param @param savepath 文件存储路径
* @param @return
* @param @throws IOException
* @param @throws MyException
* @return byte[] 字符数组
* @throws
*/
public static byte[] fdfsDownload(String savepath) throws IOException, MyException{
byte[] bs = null;
//存储组
String group = "";
//存储路径
String path = "";
try{
//第二个"/"索引位置
int secondindex = savepath.indexOf("/", 2);
//类似:group0
group = savepath.substring(1, secondindex);
//类似:M00/00/00/wKgBaFv9Ad-Abep_AAUtbU7xcws013.png
path = savepath.substring(secondindex + 1);
}catch (Exception e) {
throw new RuntimeException("传入文件存储路径不正确!格式例如:/group1/M00/00/00/wKgBaFv9Ad-Abep_AAUtbU7xcws013.png");
}
//返回byte数组
bs = storageClient.download_file(group, path);
return bs;
}
/**
*
* @Title: fdfsDeleteFile
* @Description: 删除文件
* @param @param savepath 文件存储路径
* @param @return
* @param @throws IOException
* @param @throws MyException
* @return boolean 返回true表示删除成功
* @throws
*/
public static boolean fdfsDeleteFile(String savepath) throws IOException, MyException{
//存储组
String group = "";
//存储路径
String path = "";
try{
//第二个"/"索引位置
int secondindex = savepath.indexOf("/", 2);
group = savepath.substring(1, secondindex);
path = savepath.substring(secondindex + 1);
}catch (Exception e) {
throw new RuntimeException("传入文件存储路径不正确!格式例如:/group1/M00/00/00/wKgBaFv9Ad-Abep_AAUtbU7xcws013.png");
}
//删除文件,0表示删除成功
int result = storageClient.delete_file(group, path);
if(result != 0){
throw new RuntimeException("删除文件失败:文件路径不对或者文件已删除!");
}
return true;
}
/**
*
* @Title: fdfdFileInfo
* @Description: 返回文件信息
* @param @param savepath 文件存储路径
* @param @return
* @param @throws IOException
* @param @throws MyException
* @return FileInfo 文件信息
* @throws
*/
public static FileInfo fdfdFileInfo(String savepath) throws IOException, MyException {
String group ="";
String path = "";
try{
//第二个"/"索引位置
int secondindex = savepath.indexOf("/", 2);
group = savepath.substring(1, secondindex);
path = savepath.substring(secondindex + 1);
}catch (Exception e) {
throw new RuntimeException("传入文件存储路径不正确!格式例如:/group1/M00/00/00/wKgBaFv9Ad-Abep_AAUtbU7xcws013.png");
}
FileInfo fileInfo = storageClient.get_file_info(group, path);
// //服务器内部有时间差
// //方式一:使用客服端时间
// int create_timestamp_client= (int) (System.currentTimeMillis() / 1000L);
// System.out.println("方式一:使用客服端时间"+new Date());
// //方式二:使用服务器时间补上时间差
// int create_timestamp = (int) (fileInfo.getCreateTimestamp().getTime()/1000+44060);
// fileInfo .setCreateTimestamp(create_timestamp);
// System.out.println(System.currentTimeMillis()/1000 -create_timestamp);
return fileInfo;
}
}
4.测试类文档
package com.hk;
import com.hk.utils.FastDfsUtil;
import org.csource.common.MyException;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* @Author bigbeardhk
* @Date 2020/9/17 16:36
* 对FastDfsUtil工具类方法的测试
*/
public class Test2FastDfsUtil {
/**
*
* @throws IOException
* @throws MyException
* fdfsUpload(InputStream inputStream, String filename)的测试
* fileDownPath可以带文件后缀,也不可以不带文件后缀
*/
@Test
public void test2fdfsUploadByInputStream() throws IOException, MyException {
//通过文件流上传文件
String fileDownPath="C:\Users\user\Desktop\dfs_test\upload\Snipaste_2020-09-17_14-36-13.png";
System.out.println(FastDfsUtil.fdfsUpload(new FileInputStream(new File(fileDownPath)), fileDownPath));
}
/**
* @throws IOException
* @throws MyException
* FastDfsUtil.fdfsUpload(fileDownPath)的测试
* fileDownPath可以带文件后缀,也不可以不带文件后缀
*/
@Test
public void test2fdfsUploadByPath() throws IOException, MyException {
String fileDownPath="C:\Users\user\Desktop\dfs_test\upload\Snipaste_2020-09-17_14-36-13.png";
//上传文件
String uri=FastDfsUtil.fdfsUpload(fileDownPath);
System.out.println("存储路径:" + uri);
StringBuilder url=new StringBuilder("http://192.168.223.140:8888/");
//可以直接查看图片txt文件或其它文件下载
System.out.println( "图片地址或其它文件下载地址:"+url.append(uri));
}
/**
*
* @throws IOException
* @throws MyException
* fdfsDownload(String savepath, String localPathDirectory)的测试
*下载文件到指定fileDownPath参数路径下
*/
@Test
public void test2fdfsDownload() throws IOException, MyException {
//注意这两个地址的格式
String filePath="/group1/M00/00/00/wKjfjF9iW8GAPdU8AAmgqzKHw0o924.png";
//最后面地址不带斜杠,下载后文件名默认为wKjfjF9iW8GAPdU8AAmgqzKHw0o924.后缀的格式
String fileDownPath= "C:\Users\user\Desktop\dfs_test\downloads";
//下载文件到本地
System.out.println(FastDfsUtil.fdfsDownload(filePath, fileDownPath));
}
/**
*
* @throws IOException
* @throws MyException
*FastDfsUtil.fdfsDownload(filePath)的测试
* 下载文件并以字节数组的方式返回
*/
@Test
public void test2fdfsDownloadByByte() throws IOException, MyException {
String filePath="/group1/M00/00/00/wKjfjF9iJIKALbptAAABboeEngI813.jpg";
//获取文件byte[],打印字节数组长度
System.out.println(FastDfsUtil.fdfsDownload(filePath).length);
}
/**
*
* @throws IOException
* @throws MyException
* fdfsDeleteFile(String savepath)方法的测试
*/
@Test
public void test2fdfsDeleteFile() throws IOException, MyException {
//删除文件
String filePathByDelete="/group1/M00/00/00/wKjfjF9iYsOAa0-ZAAmgqzKHw0o359.png";
//删除成功返回true
//失败:报错:java.lang.RuntimeException: 删除文件失败:文件路径不对或者文件已删除!
System.out.println(FastDfsUtil.fdfsDeleteFile(filePathByDelete));
}
/**
* @throws IOException
* @throws MyException
* fdfdFileInfo(String savepath)的测试
* 测试结果:
* source_ip_addr:storage的服务器地址
* file_size:文件大小
* create_timestamp:服务器内部时间,即文件上传的时间
* crc32:冗余校验码
* source_ip_addr = 192.168.223.140, file_size = 18380, create_timestamp = 2020-09-17 05:37:48, crc32 = -1182993482
*
*/
@Test
public void test2fdfdFileInfo() throws IOException, MyException {
//文件信息
String uri="/group1/M00/00/00/wKjfjF9ihayAX4vLAABHzLl887Y769.png";
System.out.println(FastDfsUtil.fdfdFileInfo(uri).toString());
}
}