一、添加所需的jar包
由于使用Maven对项目进行管理,而Maven中央仓库没有所需的jar包
首先从https://github.com/happyfish100/fastdfs-client-java下载源码
解压后导入工程
右键工程–>Run As–>Maven install
至此,本地仓库中已经添加了所需的jar包
随后,在对应项目的pom文件中添加依赖即可成功导入jar包
二、源码
import java.io.IOException;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.junit.Test;
public class FastDFSTest {
@Test
public void testUpload() throws IOException, MyException {
// 1、把FastDFS提供的jar包添加到工程中
// 2、初始化全局配置。加载一个配置文件。
ClientGlobal.init("properties/client.conf");
// 3、创建一个TrackerClient对象。
TrackerClient trackerClient = new TrackerClient();
// 4、创建一个TrackerServer对象。
TrackerServer trackerServer = trackerClient.getConnection();
// 5、声明一个StorageServer对象,null。
StorageServer storageServer = null;
// 6、获得StorageClient对象。
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
// 7、直接调用StorageClient对象方法上传文件即可。
String[] strings = storageClient.upload_file("G:\\Desert.jpg", "jpg", null);
for (String string : strings) {
System.out.println(string);
}
}
}
ClientGlobal.init("properties/client.conf");
中指定的client.conf的内容为
tracker_server=192.168.55.129:22122
即 tracker 服务的 ip 及端口号
三、调试
右键–>Debug As–>JUnit Test 报错
考虑是防火墙未开放对应端口22122
开放对应端口步骤
1 修改iptables
2 重启iptables服务
3 再次调试依然报错
经查为storage服务器的端口未开放
fdfs的storage服务器对应的配置文件为storage.conf
其中port指定了storage服务对应的端口。
开放该端口后再次运行,控制台成功打印消息
将返回的字符串数组拼接,衔接在storage服务器的ip后,即对应上传文件的url
访问对应url显示图片表明上传成功