首先添加相应的jar包:
<!-- 添加FastDFS客户端的引用 --> <dependency> <groupId>fastdfs_client</groupId> <artifactId>fastdfs_client</artifactId> <version>1.25</version> </dependency> <!-- 文件上传组件 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
测试类:
配置文件:client.conf
tracker_server=192.168.25.133:22122
public class TestFastDFS { @Test public void uploadFile() throws Exception { //1、向工程中添加jar包 //2、创建一个配置文件。配置tracker服务器地址 //3、加载配置文件 ClientGlobal.init("D:/client.conf"); //4、创建一个TrackerClient对象。 TrackerClient trackerClient = new TrackerClient(); //5、使用TrackerClient对象获得trackerserver对象。 TrackerServer trackerServer = trackerClient.getConnection(); //6、创建一个StorageServer的引用null就可以。 StorageServer storageServer = null; //7、创建一个StorageClient对象。trackerserver、StorageServer两个参数。 StorageClient storageClient = new StorageClient(trackerServer, storageServer); //8、使用StorageClient对象上传文件。 String[] strings = storageClient.upload_file("D:/200811281555127886.jpg", "jpg", null); for (String string : strings) { System.out.println(string); } } }
工具类:
public class FastDFSClient { private TrackerClient trackerClient = null; private TrackerServer trackerServer = null; private StorageServer storageServer = null; private StorageClient1 storageClient = null; public FastDFSClient(String conf) throws Exception { if (conf.contains("classpath:")) { conf = conf.replace("classpath:", this.getClass().getResource("/").getPath()); } ClientGlobal.init(conf); trackerClient = new TrackerClient(); trackerServer = trackerClient.getConnection(); storageServer = null; storageClient = new StorageClient1(trackerServer, storageServer); } /** * 上传文件方法 * <p>Title: uploadFile</p> * <p>Description: </p> * @param fileName 文件全路径 * @param extName 文件扩展名,不包含(.) * @param metas 文件扩展信息 * @return * @throws Exception */ public String uploadFile(String fileName, String extName, NameValuePair[] metas) throws Exception { String result = storageClient.upload_file1(fileName, extName, metas); return result; } public String uploadFile(String fileName) throws Exception { return uploadFile(fileName, null, null); } public String uploadFile(String fileName, String extName) throws Exception { return uploadFile(fileName, extName, null); } /** * 上传文件方法 * <p>Title: uploadFile</p> * <p>Description: </p> * @param fileContent 文件的内容,字节数组 * @param extName 文件扩展名 * @param metas 文件扩展信息 * @return * @throws Exception */ public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throws Exception { String result = storageClient.upload_file1(fileContent, extName, metas); return result; } public String uploadFile(byte[] fileContent) throws Exception { return uploadFile(fileContent, null, null); } public String uploadFile(byte[] fileContent, String extName) throws Exception { return uploadFile(fileContent, extName, null); } }