一、加入Maven依赖
<dependency> <groupId>org.csource</groupId> <artifactId>fastdfs-client-java</artifactId> <version>1.27-SNAPSHOT</version> </dependency>
二、客户端代码
@RunWith(SpringRunner.class) @SpringBootTest public class GmallManageWebApplicationTests { @Test public void contextLoads() throws IOException, MyException { // 配置fdfs的全局链接地址 String tracker = GmallManageWebApplicationTests.class.getResource("/tracker.conf").getPath();// 获得配置文件的路径 ClientGlobal.init(tracker); TrackerClient trackerClient = new TrackerClient(); // 获得一个trackerServer的实例 TrackerServer trackerServer = trackerClient.getConnection(); // 通过tracker获得一个Storage链接客户端 StorageClient storageClient = new StorageClient(trackerServer,null); String[] uploadInfos = storageClient.upload_file("d:/a.jpg", "jpg", null); String url = "http://192.168.2.128"; for (String uploadInfo : uploadInfos) { url += "/"+uploadInfo; //url = url + uploadInfo; } System.out.println(url); } }
tracker.conf
tracker_server=192.168.2.128:22122 # 连接超时时间,针对socket套接字函数connect,默认为30秒 connect_timeout=30000 # 网络通讯超时时间,默认是60秒 network_timeout=60000
控制台打印:
http://192.168.2.128/group1/M00/00/00/wKgCgF2xkrOANCrrAAxpifD7458779.jpg
此路径在浏览器中访问即可访问我们上传的图片。
工具类
public class PmsUploadUtil { public static String uploadImage(MultipartFile multipartFile) { String imgUrl = "http://192.168.2.128"; // 上传图片到服务器 // 配置fdfs的全局链接地址 String tracker = PmsUploadUtil.class.getResource("/tracker.conf").getPath();// 获得配置文件的路径 try { ClientGlobal.init(tracker); } catch (Exception e) { e.printStackTrace(); } TrackerClient trackerClient = new TrackerClient(); // 获得一个trackerServer的实例 TrackerServer trackerServer = null; try { trackerServer = trackerClient.getConnection(); } catch (IOException e) { e.printStackTrace(); } // 通过tracker获得一个Storage链接客户端 StorageClient storageClient = new StorageClient(trackerServer,null); try { byte[] bytes = multipartFile.getBytes();// 获得上传的二进制对象 // 获得文件后缀名 String originalFilename = multipartFile.getOriginalFilename();// a.jpg System.out.println(originalFilename); int i = originalFilename.lastIndexOf("."); String extName = originalFilename.substring(i+1); String[] uploadInfos = storageClient.upload_file(bytes, extName, null); for (String uploadInfo : uploadInfos) { imgUrl += "/"+uploadInfo; } } catch (Exception e) { e.printStackTrace(); } return imgUrl; } }
在springmvc文件上传控制器中我们只需要用MultipartFile multipartFile
参数去接收就可以了。