fastdfs客户端工具类
pom:
<dependency> <groupId>org.csource</groupId> <artifactId>fastdfs-client-java</artifactId> <version>1.25</version> </dependency>
百度云链接:https://pan.baidu.com/s/1i3yaSbb0pY7n0FiZ71XePA 提取码:c68d
application.yml
fastdfs:
tracker_server: 192.168.100.105:22122
connect_timeout: 5
network_timeout: 30
charset: UTF-8
http:
secret_key: FastDFS1234567890
tracker_http_port: 8081
anti_steal:
check_token: no
代码1:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public final class FastDFSHelper { private static final Logger logger = LoggerFactory.getLogger(FastDFSHelper.class); private static TrackerClient trackerClient; static { try { ClientGlobal.init("fdfs_client.conf"); trackerClient = new TrackerClient(); } catch (IOException | MyException e) { logger.error("error", e); } } /** * 向FastDFS上传文件 * * @param localFilename 本地文件名 * @return 上传成功,返回组名和该文件在FastDFS中的名称;上传失败,返回null */ public static void uploadFile(String localFilename) { TrackerServer trackerServer; try { trackerServer = trackerClient.getConnection(); } catch (IOException e) { logger.error("error", e); return; } StorageClient storageClient = new StorageClient(trackerServer, null); try { String[] arr = storageClient.upload_file(localFilename, null, null); if (arr == null || arr.length != 2) { logger.error("向FastDFS上传文件失败"); } else { logger.info("向FastDFS上传文件成功"); } } catch (IOException | MyException e) { logger.error("error", e); } finally { closeTrackerServer(trackerServer); } } /** * 从FastDFS下载文件 * * @param localFilename 本地文件名 * @param groupName 文件在FastDFS中的组名 * @param remoteFilename 文件在FastDFS中的名称 */ public static void downloadFile(String localFilename, String groupName, String remoteFilename) { TrackerServer trackerServer; try { trackerServer = trackerClient.getConnection(); } catch (IOException e) { logger.error("error", e); return; } StorageClient storageClient = new StorageClient(trackerServer, null); File file = new File(localFilename); try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) { byte[] content = storageClient.download_file(groupName, remoteFilename); if (content == null || content.length == 0) { logger.error("文件大小为空!"); boolean flag = file.delete(); logger.info("删除文件结果:{}", flag); return; } bos.write(content); logger.info("成功下载文件: " + localFilename); } catch (IOException | MyException e) { logger.error("error", e); } finally { closeTrackerServer(trackerServer); } } /** * 从FastDFS删除文件 * * @param localFilename 本地文件名 * @param groupName 文件在FastDFS中的组名 * @param remoteFilename 文件在FastDFS中的名称 */ public static void deleteFile(String localFilename, String groupName, String remoteFilename) { TrackerServer trackerServer; try { trackerServer = trackerClient.getConnection(); } catch (IOException e) { logger.error("error", e); return; } StorageClient storageClient = new StorageClient(trackerServer, null); try { int i = storageClient.delete_file(groupName, remoteFilename); if (i == 0) { logger.info("FastDFS删除文件成功"); } else { logger.info("FastDFS删除文件失败"); } } catch (IOException | MyException e) { logger.error("error", e); } finally { closeTrackerServer(trackerServer); } } private static void closeTrackerServer(TrackerServer trackerServer) { try { if (trackerServer != null) { logger.info("关闭trackerServer连接"); trackerServer.close(); } } catch (IOException e) { logger.error("error", e); } } }
代码2:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.sunward.car.util; import org.apache.commons.io.IOUtils; import org.csource.common.NameValuePair; import org.csource.fastdfs.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.net.ssl.HttpsURLConnection; import java.io.*; import java.net.InetSocketAddress; import java.net.URL; import java.util.Iterator; import java.util.Map; import java.util.UUID; /** * @author chong.zuo * @date 2021/5/19 22:34 */ @Component public class FastDFSClient { private static final Logger LOG = LoggerFactory.getLogger(FastDFSClient.class); private static final String GROUP_NAME = "market1"; private static StorageClient storageClient; private static String trackerServerIP; @Value("${fastdfs.tracker_server}") public void setTrackerServerIP(String tracker_server) { trackerServerIP = tracker_server; } private static int trackerServerPort; @Value("${fastdfs.port}") public void setPort(int port) { trackerServerPort = port; } private static int connectTimeout; @Value("${fastdfs.connect_timeout}") public void setConnectTimeout(int connect_timeout) { connectTimeout = connect_timeout; } private static int networkTimeout; @Value("${fastdfs.network_timeout}") public void setNetworkTimeout(int network_timeout) { networkTimeout = network_timeout; } private static String charsetStr; @Value("${fastdfs.charset}") public void setCharsetStr(String charset) { charsetStr = charset; } private static String secretkey; @Value("${fastdfs.http.secret_key}") public void setSecretkey(String secret_key) { secretkey = secret_key; } private static int trackerHttpPort; @Value("${fastdfs.http.tracker_http_port}") public void setTrackerHttpPort(int tracker_http_port) { trackerHttpPort = tracker_http_port; } /** * 初始化fastdfs客户端 * @return * @throws IOException */ public static StorageClient initClient() throws IOException { ClientGlobal.setG_connect_timeout(connectTimeout); ClientGlobal.setG_network_timeout(networkTimeout); ClientGlobal.setG_anti_steal_token(false); ClientGlobal.setG_charset(charsetStr); ClientGlobal.setG_secret_key(null); ClientGlobal.setG_tracker_http_port(trackerHttpPort); InetSocketAddress[] tracker_servers = new InetSocketAddress[1]; tracker_servers[0] = new InetSocketAddress(trackerServerIP, trackerServerPort); ClientGlobal.setG_tracker_group(new TrackerGroup(tracker_servers)); TrackerClient trackerClient = new TrackerClient(ClientGlobal.g_tracker_group); TrackerServer trackerServer = trackerClient.getConnection(); StorageServer storageServer = trackerClient.getStoreStorage(trackerServer); return new StorageClient(trackerServer, storageServer); } /** * 获取StorageClient * @return */ public static StorageClient getClient(){ if(storageClient == null){ synchronized (FastDFSClient.class){ try{ if(storageClient==null){ storageClient = initClient(); } }catch (Exception e){ LOG.error("storageClient创建失败...." + storageClient,e); } } } return storageClient; } /** * 上传文件 * @param file * @param fileName * @param metaList * @return */ public static String[] uploadFile(StorageClient client, File file, String fileName, Map<String,String> metaList) { try { byte[] buff = IOUtils.toByteArray(new FileInputStream(file)); NameValuePair[] nameValuePairs = null; if (metaList != null) { nameValuePairs = new NameValuePair[metaList.size()]; int index = 0; for (Iterator<Map.Entry<String,String>> iterator = metaList.entrySet().iterator(); iterator.hasNext();) { Map.Entry<String,String> entry = iterator.next(); String name = entry.getKey(); String value = entry.getValue(); nameValuePairs[index++] = new NameValuePair(name,value); } } return client.upload_file(GROUP_NAME,buff,fileName,nameValuePairs); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 将网络地址图片上传至fastdfs * @param urlString * @return * @throws Exception */ public static String uploadFileByUrl(StorageClient client, String urlString) throws Exception{ URL url = new URL(urlString); FileOutputStream fos = null; HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setHostnameVerifier(new TrustAnyHostnameVerifier()); conn.connect(); File file = File.createTempFile(UUID.randomUUID().toString().replace("-",""), ".jpg"); fos = new FileOutputStream(file); BufferedInputStream bis =new BufferedInputStream(conn.getInputStream()); byte[] data = new byte[2048]; int len = 0; int sum = 0; while ((len = bis.read(data)) != -1) { fos.write(data, 0, len); } //FastDFSClient client = new FastDFSClient(); String[] result = FastDFSClient.uploadFile(client, file, "jpg",null); fos.flush(); fos.close(); bis.close(); conn.disconnect(); //http://192.168.126.110/group1/M00/00/00/wKh-bmCgvm2AVJItAAMDpg8cMaY364.jpg return "http://"+trackerServerIP.split(":")[0]+"/"+result[0]+"/"+result[1]; } /** * 删除文件 * @param storageClient * @param groupname * @param fileId 文件ID(上传文件成功后返回的ID) * @return */ public int deleteFile(StorageClient storageClient, String groupname,String fileId) { try { return storageClient.delete_file(groupname,fileId); } catch (Exception e) { e.printStackTrace(); } return -1; } /** * 下载文件 * @param fileId 文件ID(上传文件成功后返回的ID) * @param outFile 文件下载保存位置 * @return */ public int downloadFile(StorageClient storageClient, String groupName,String fileId, File outFile) { FileOutputStream fos = null; try { byte[] content = storageClient.download_file(groupName,fileId); fos = new FileOutputStream(outFile); InputStream ips = new ByteArrayInputStream(content); IOUtils.copy(ips,fos); return 0; } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } return -1; } }