Java 客戶端操作 FastDFS 實現檔案上傳下載替換刪除功能
阿新 • • 發佈:2020-10-19
FastDFS 的作者餘慶先生已經為我們開發好了 Java 對應的 SDK。這裡需要解釋一下:作者餘慶並沒有及時更新最新的 Java SDK 至 Maven 中央倉庫,目前中央倉庫最新版仍舊是 1.27 版。所以我們需要通過 Github:https://github.com/happyfish100/fastdfs-client-java 下載專案原始碼,再通過命令 mvn clean install
編譯打包匯入 Maven 倉庫使用即可。
接下來我們通過 Java API 操作 FastDFS 實現檔案的上傳、下載、替換、刪除、查詢元資料、查詢詳情等功能。
文中案例已同步至:
Github:https://github.com/imrhelloworld/fastdfs-javaGitee:https://gitee.com/imrhelloworld/fastdfs-java
建立專案
新增依賴
在專案的 pom.xml 中新增以下依賴。因為我們需要一些常用工具包和單元測試,所以需要引入它們。
<!-- fastdfs java client --> <dependency> <groupId>org.csource</groupId> <artifactId>fastdfs-client-java</artifactId> <version>1.29-SNAPSHOT</version> </dependency> <!-- apache commons lang3 工具包 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.11</version> </dependency> <!-- junit 單元測試 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>test</scope> </dependency>
編寫配置檔案
fdfs_client.conf
# 超時時間 connect_timeout = 10 network_timeout = 30 # 編碼字符集 charset = UTF-8 # tracker 伺服器 HTTP 協議下暴露的埠 http.tracker_http_port = 8080 # tracker 伺服器的 IP 和埠 tracker_server = 192.168.10.101:22122
工具類
package org.example.client; import org.apache.commons.lang3.StringUtils; import org.csource.common.MyException; import org.csource.common.NameValuePair; import org.csource.fastdfs.*; import java.io.*; /** * FastDFS 分散式檔案系統 Java 客戶端工具類 * 具體功能:檔案上傳、下載、替換、刪除、查詢檔案元資料、檢視檔案詳情 */ public class FastDFSClient { // 獲取配置檔案地址 private static final String CONF_FILENAME = Thread.currentThread() .getContextClassLoader().getResource("").getPath() + "fdfs_client.conf"; // Storage 儲存伺服器客戶端 private static StorageClient storageClient = null; static { try { // 載入配置檔案 ClientGlobal.init(CONF_FILENAME); // 初始化 Tracker 客戶端 TrackerClient trackerClient = new TrackerClient(ClientGlobal.g_tracker_group); // 初始化 Tracker 服務端 TrackerServer trackerServer = trackerClient.getTrackerServer(); // 初始化 Storage 服務端 StorageServer storageServer = trackerClient.getStoreStorage(trackerServer); // 初始化 Storage 客戶端 storageClient = new StorageClient(trackerServer,storageServer); } catch (IOException e) { e.printStackTrace(); } catch (MyException e) { e.printStackTrace(); } } /** * 檔案上傳 * * @param inputStream 上傳的檔案的位元組輸入流 * @param fileName 上傳的檔案的原始名 * @return */ public static String[] uploadFile(InputStream inputStream,String fileName) { try { // 準備位元組陣列 byte[] fileBuff = null; // 檔案元資料 NameValuePair[] metaList = null; if (inputStream != null) { // 檢視檔案的長度 int len = inputStream.available(); // 初始化元資料陣列 metaList = new NameValuePair[2]; // 第一組元資料,檔案的原始名稱 metaList[0] = new NameValuePair("file_name",fileName); // 第二組元資料,檔案的長度 metaList[1] = new NameValuePair("file_length",String.valueOf(len)); // 建立對應長度的位元組陣列 fileBuff = new byte[len]; // 將輸入流中的位元組內容,讀到位元組陣列中 inputStream.read(fileBuff); } /* 上傳檔案。 引數含義:要上傳的檔案的內容(使用位元組陣列傳遞),上傳的檔案的型別(副檔名),元資料 */ String[] fileids = storageClient.upload_file(fileBuff,getFileExt(fileName),metaList); return fileids; } catch (IOException e) { e.printStackTrace(); } catch (MyException e) { e.printStackTrace(); } return null; } /** * 檔案上傳 * * @param file 上傳的檔案 * @param fileName 上傳的檔案的原始名 * @return */ public static String[] uploadFile(File file,String fileName) { try (FileInputStream fis = new FileInputStream(file)) { return uploadFile(fis,fileName); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 獲取檔案字尾名(不帶點) * * @param fileName * @return 如:"jpg" or "" */ private static String getFileExt(String fileName) { if (StringUtils.isBlank(fileName) || !fileName.contains(".")) { return ""; } return fileName.substring(fileName.lastIndexOf(".") + 1); // 不帶最後的點 } /** * 獲取檔案詳情 * * @param groupName 組/卷名,預設值:group1 * @param remoteFileName 檔名,例如:"M00/00/00/wKgKZl9tkTCAJAanAADhaCZ_RF0495.jpg" * @return 檔案詳情 */ public static FileInfo getFileInfo(String groupName,String remoteFileName) { try { return storageClient.get_file_info(groupName == null ? "group1" : groupName,remoteFileName); } catch (IOException e) { e.printStackTrace(); } catch (MyException e) { e.printStackTrace(); } return null; } /** * 獲取元資料 * * @param groupName 組/卷名,預設值:group1 * @param remoteFileName 檔名,例如:"M00/00/00/wKgKZl9tkTCAJAanAADhaCZ_RF0495.jpg" * @return 檔案的元資料陣列 */ public static NameValuePair[] getMetaData(String groupName,String remoteFileName) { try { // 根據組名和檔名通過 Storage 客戶端獲取檔案的元資料陣列 return storageClient.get_metadata(groupName == null ? "group1" : groupName,remoteFileName); } catch (IOException e) { e.printStackTrace(); } catch (MyException e) { e.printStackTrace(); } return null; } /** * 檔案下載 * * @param groupName 組/卷名,預設值:group1 * @param remoteFileName 檔名,例如:"M00/00/00/wKgKZl9tkTCAJAanAADhaCZ_RF0495.jpg" * @return 檔案的位元組輸入流 */ public static InputStream downloadFile(String groupName,String remoteFileName) { try { // 根據組名和檔名通過 Storage 客戶端獲取檔案的位元組陣列 byte[] bytes = storageClient.download_file(groupName == null ? "group1" : groupName,remoteFileName); // 返回位元組流物件 InputStream inputStream = new ByteArrayInputStream(bytes); return inputStream; } catch (IOException e) { e.printStackTrace(); } catch (MyException e) { e.printStackTrace(); } return null; } /** * 檔案刪除 * * @param groupName 組/卷名,預設值:group1 * @param remoteFileName 檔名,例如:"M00/00/00/wKgKZl9tkTCAJAanAADhaCZ_RF0495.jpg" * @return 0為成功,非0為失敗 */ public static int deleteFile(String groupName,String remoteFileName) { int result = -1; try { // 根據組名和檔名通過 Storage 客戶端刪除檔案 result = storageClient.delete_file(groupName == null ? "group1" : groupName,remoteFileName); } catch (IOException e) { e.printStackTrace(); } catch (MyException e) { e.printStackTrace(); } return result; } /** * 修改一個已經存在的檔案 * * @param oldGroupName 舊組名 * @param oldFileName 舊檔名 * @param file 新檔案 * @param fileName 新檔名 * @return */ public static String[] modifyFile(String oldGroupName,String oldFileName,File file,String fileName) { // 先上傳 String[] fileids = uploadFile(file,fileName); if (fileids == null) { return null; } // 再刪除 int delResult = deleteFile(oldGroupName,oldFileName); if (delResult != 0) { return null; } return fileids; } }
測試
檔案上傳
// 檔案上傳 @Test public void testUploadFile() { String[] fileids = FastDFSClient.uploadFile(new File("D:/china.jpg"),"china.jpg"); for (String fileid : fileids) { System.out.println("fileid = " + fileid); } }
返回值
fileid = group1 fileid = M00/00/00/wKgKZl9xMdiAcOLdAADhaCZ_RF0096.jpg
檔案詳情
// 檢視檔案詳情 @Test public void testGetFileInfo() { FileInfo fileInfo = FastDFSClient.getFileInfo("group1","M00/00/00/wKgKZl9xMdiAcOLdAADhaCZ_RF0096.jpg"); System.out.println("fileInfo = " + fileInfo); }
返回值:
fileInfo = fetch_from_server = false,file_type = 1,source_ip_addr = 192.168.10.102,file_size = 57704,create_timestamp = 2020-09-28 08:44:08,crc32 = 645874781
檔案元資料
// 獲取檔案資料 @Test public void testGetMetaData() { NameValuePair[] metaDatas = FastDFSClient.getMetaData("group1","M00/00/00/wKgKZl9xMdiAcOLdAADhaCZ_RF0096.jpg"); for (NameValuePair metaData : metaDatas) { System.out.println(metaData.getName() + "---" + metaData.getValue()); } }
返回值:
file_length---57704 file_name---china.jpg
檔案下載
// 檔案下載 @Test public void testDownloadFile() { InputStream is = FastDFSClient.downloadFile("group1","M00/00/00/wKgKZl9xMdiAcOLdAADhaCZ_RF0096.jpg"); try (FileOutputStream fos = new FileOutputStream("D:/wKgKZl9xMdiAcOLdAADhaCZ_RF0096.jpg")) { int len = 0; byte[] bytes = new byte[1024]; while ((len = is.read(bytes)) != -1) { fos.write(bytes,len); fos.flush(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
檔案刪除
// 檔案刪除 @Test public void testDeleteFile() { int result = FastDFSClient.deleteFile("group1","M00/00/00/wKgKZl9xMdiAcOLdAADhaCZ_RF0096.jpg"); System.out.println("result = " + result); }
返回值:
result = 0
檔案替換
// 檔案替換 @Test public void testModifyFile() { String[] fileids = FastDFSClient.modifyFile("group1","M00/00/00/wKgKZl9xOS2ASdu8AADhaCZ_RF0898.jpg",new File("D:/mhw.jpg"),"mhw.jpg"); for (String fileid : fileids) { System.out.println("fileid = " + fileid); } }
返回值:
fileid = group1 fileid = M00/00/00/wKgKZl9xOeaAFO00AACmo7QBGtA298.jpg
至此 Java 客戶端操作 FastDFS 實現檔案上傳下載替換刪除等操作就到這裡,下一篇我們帶大家搭建 FastDFS 的叢集環境,多 Tracker 多 Storage 然後通過 Nginx 代理。
到此這篇關於Java 客戶端操作 FastDFS 實現檔案上傳下載替換刪除功能的文章就介紹到這了,更多相關java 檔案上傳下載替換刪除內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!