在上篇文章給大家介紹了FastDFS安裝和配置整合Nginx-1.13.3的方法,大家可以點擊查看下。
今天使用Java代碼實現文件的上傳和下載。對此作者提供了Java API支持,下載fastdfs-client-java將源碼添加到項目中。或者在Maven項目pom.xml文件中添加依賴
1
2
3
4
5
|
<dependency> <groupId>org.csource</groupId> <artifactId>fastdfs-client-java</artifactId> <version> 1.27 -SNAPSHOT</version> </dependency> |
一 : 添加配置文件
當完成以上操作之后可以添加鏈接FastDFS服務器的配置文件 fastdfs-client.properties
1
2
3
4
5
6
7
|
fastdfs.connect_timeout_in_seconds = 5 fastdfs.network_timeout_in_seconds = 30 fastdfs.charset = UTF- 8 fastdfs.http_anti_steal_token = false fastdfs.http_secret_key = FastDFS1234567890 fastdfs.http_tracker_http_port = 80 fastdfs.tracker_servers = 192.168 . 1.7 : 22122 |
因為項目中只使用properties 格式文件,如果需要更多的配置信息,可以查看官方的配置信息
注: 1. 其他的配置項為可選,fastdfs.tracker_servers 為必須選項
2. 多個tracker_servers可以使用逗號“ , ”分隔
二 : 加載配置文件
1. 測試加載配置文件
1
2
3
4
5
6
|
@Test public void initConifg() throws Exception { // 加載配置文件 ClientGlobal.initByProperties( "config/fastdfs-client.properties" ); System.out.println( "ClientGlobal.configInfo():" + ClientGlobal.configInfo()); } |
2. 輸出結果
1
2
3
4
5
6
7
8
9
|
ClientGlobal.configInfo():{ g_connect_timeout(ms) = 5000 g_network_timeout(ms) = 30000 g_charset = UTF- 8 g_anti_steal_token = false g_secret_key = FastDFS1234567890 g_tracker_http_port = 80 trackerServers = 192.168 . 1.7 : 22122 } |
當出現上面和配置文件一致的輸出結果時候,說明加載配置文件已經成功。
三:功能實現
由于是使用Junit做測試,為了方便在開始執行之前,初始化配置文件和獲取連接,同時沒有捕獲異常全部拋出
1.初始化連接信息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
//成員變量 TrackerServer trackerServer = null ; StorageServer storageServer = null ; StorageClient storageClient = null ; /** * 初始化連接信息 * @author: wrh45 * @date: 2017年8月5日下午8:08:57 */ @Before public void init() throws Exception { // 加載配置文件 ClientGlobal.initByProperties( "config/fastdfs-client.properties" ); // 獲取連接 TrackerClient trackerClient = new TrackerClient(); trackerServer = trackerClient.getConnection(); storageClient = new StorageClient(trackerServer, storageServer); } |
注: 如果出現連接超時異常:java.net.SocketTimeoutException: connect timed out
1 .查看服務器地址和端口是否正確
? 2 .請查看服務器TrackerServer和StorageServer服務端口是否開啟。默認為22122和23000
2.上傳文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
/** * 上傳圖片 * @throws Exception * @author: wrh45 * @date: 2017年8月5日下午7:09:23 */ @Test public void uploadFileOfByte() throws Exception { // 獲取文件字節信息 file = new File( "src/test/resources/pic/Ace.jpg" ); FileInputStream inputStream = new FileInputStream(file); byte [] file_buff = new byte [( int ) file.length()]; inputStream.read(file_buff); // 獲取文件擴展名 String fileName = file.getName(); String extName = null ; if (fileName.contains( "." )) { extName = fileName.substring(fileName.lastIndexOf( "." ) + 1 ); } else { return ; } // 圖片元數據,如果設置為空,那么服務器上不會生成-m的原數據文件 NameValuePair[] meta_list = new NameValuePair[ 2 ]; meta_list[ 0 ] = new NameValuePair( "fileName" , "測試專用" ); meta_list[ 1 ] = new NameValuePair( "length" , "測試專用" ); // 文件上傳,返回組名和訪問地址 String[] upload_file = storageClient.upload_file(file_buff, extName, meta_list); System.out.println(Arrays.asList(upload_file)); } |
下面是執行結果
已經將圖片上傳到服務器,同時返回了圖片地址。那么通過這個地址試試能否訪問
OK,在瀏覽器輸入地址后,成功返回了圖片信息
3.下載文件
這里通過storageClient下載文件,然后將數據存儲到本地。如果通過瀏覽器下載,同理將數據寫入文件即可
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
/** * 下載圖片 * @throws Exception * @author: wrh45 * @date: 2017年8月5日下午8:09:10 */ @Test public void downLoadFile() throws Exception { // 下載文件,返回字節數組 byte [] file_buff = storageClient.download_file( "group1" , "M00/00/00/wKgBB1l-EwyAGvxuAAWkdYkPHEE854.jpg" ); // 將數據寫文件中 File file = new File( "src/test/resources/pic/Ace2.jpg" ); FileOutputStream outStream = new FileOutputStream(file); outStream.write(file_buff); outStream.flush(); outStream.close(); } |
下面是執行結果,不出意外是可以成功執行的
4.獲取元數據信息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
/** * 元數據信息 * @throws Exception * @author: wrh45 * @date: 2017年8月5日下午8:09:38 */ @Test public void metaData() throws Exception { // 上傳圖片的時候,元數據若為空將無法生存-m的原數據文件。獲取時候此處將拋出NullPointerException NameValuePair[] get_metadata = storageClient.get_metadata( "group1" , "M00/00/00/wKgBB1l-EwyAGvxuAAWkdYkPHEE854.jpg" ); for (NameValuePair nameValuePair: get_metadata) { System.out.println( "name: " + nameValuePair.getName() + " value: " + nameValuePair.getValue()); } } |
以下是執行結果,獲取到的數據和上傳的數據一樣
name: fileName value: 測試專用
name: length value: 測試專用
5.獲取文件信息
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/** * 獲取文件信息 * @author: wrh45 * @date: 2017年8月7日下午9:02:47 */ @Test public void getFileInfo() throws Exception { FileInfo fileInfo = storageClient.get_file_info( "group1" , "M00/00/00/wKgBB1l-EwyAGvxuAAWkdYkPHEE854.jpg" ); System.out.println( "CRC32簽名:" + fileInfo.getCrc32()); System.out.println( "文件大小:" + fileInfo.getFileSize()); System.out.println( "服務器地址:" + fileInfo.getSourceIpAddr()); System.out.println( "創建時間:" + new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ).format(fileInfo.getCreateTimestamp())); } |
輸出結果
CRC32簽名:-1995498431
文件大小:369781
服務器地址:192.168.1.7
創建時間:2017-08-07 20-24-56
6.刪除文件
當數據測試完整之后,試試能否刪除吧
1
2
3
4
5
6
7
8
9
10
11
12
|
/** * 刪除文件 * @throws Exception * @author: wrh45 * @date: 2017年8月7日下午9:10:04 */ @Test public void deleteFile() throws Exception { // 返回0成功,否則返回錯誤嗎 int code = storageClient.delete_file( "group1" , "M00/00/00/wKgBB1l-EwyAGvxuAAWkdYkPHEE854.jpg" ); System.out.println(code); } |
刪除之后輸出結果為0,如果出現非0結果,那么返回的是錯誤代碼
以上是Java實現上傳下載等功能的代碼,如果需要可以封裝成工具類使用。
以下是個人封裝好的工具類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
|
/** * 上傳文件工具類 * @ClassName: FileUploadUtils * @author wrh45 * @date 2017年8月8日下午4:14:31 */ public class FileUploadUtils { private static TrackerClient trackerClient = null ; private static TrackerServer trackerServer = null ; private static StorageServer storageServer = null ; private static StorageClient storageClient = null ; private static final String groupName = "group1" ; static { // 加載配置文件 try { ClientGlobal.initByProperties( "config/fastdfs-client.properties" ); // System.out.println("ClientGlobal.configInfo():" + // ClientGlobal.configInfo()); } catch (IOException | MyException e) { e.printStackTrace(); System.out.println( "load config file fail" ); } } /* * 初始化連接數據 */ private static void init() { try { trackerClient = new TrackerClient(); trackerServer = trackerClient.getConnection(); storageClient = new StorageClient(trackerServer, storageServer); } catch (IOException e) { e.printStackTrace(); System.out.println("init fail"); } } /** * 上傳文件 * @param filePath 文件路徑 * @param fileName 文件名稱 * @return 文件存儲信息 * @author: wrh45 * @date: 2017年8月5日下午11:10:38 */ public static String[] uploadFile(String filePath, String fileName) { return uploadFile(null, filePath, fileName); } /** * 上傳文件 * @param fileBuff 文件字節數組 * @param fileName 文件名稱 * @return 文件存儲信息 * @author: wrh45 * @date: 2017年8月5日下午11:10:38 */ public static String[] uploadFile(byte[] fileBuff, String fileName) { return uploadFile(fileBuff, null, fileName); } /** * 上傳文件 * @param file_buff 文件字節數組 * @param filePath 文件路徑 * @param fileName 文件名稱 * @return 文件存儲信息 * @author: wrh45 * @date: 2017年8月5日下午10:58:19 */ private static String[] uploadFile(byte[] fileBuff, String filePath, String fileName) { try { if (fileBuff == null && filePath == null) { return new String[0]; } // 初始化數據 if (storageClient == null) { init(); } // 獲取文件擴展名稱 String fileExtName = ""; if (fileName != null && !"".equals(fileName) && fileName.contains(".")) { fileExtName = fileName.substring(fileName.lastIndexOf(".") + 1); } else { return new String[0]; } // 設置圖片元數據 NameValuePair[] metaList = new NameValuePair[3]; metaList[0] = new NameValuePair("fileName", fileName); metaList[1] = new NameValuePair("fileExtName", fileExtName); metaList[2] = new NameValuePair("fileSize", String.valueOf(fileBuff.length)); // 上傳文件 String[] uploadFile = null; if (fileBuff != null && filePath == null) { if (fileBuff.length == 0) { return new String[0]; } uploadFile = storageClient.upload_file(fileBuff, fileExtName, metaList); } else { //路徑匹配Windown和Linux if ("".equals(filePath) || !(filePath.matches("^[a-zA-Z]:{1}([\u4e00-\u9fa5\\w/_\\\\-]+)$") || filePath.matches("^(/[\u4e00-\u9fa5\\w_-]+)+$"))) { return new String[0]; } uploadFile = storageClient.upload_file(filePath, fileExtName, metaList); } return uploadFile == null ? new String[0] : uploadFile; } catch (Exception e) { e.printStackTrace(); } finally { try { if (trackerServer != null) { trackerServer.close(); trackerServer = null; } if (storageServer != null) { storageServer.close(); storageServer = null; } } catch (IOException e) { e.printStackTrace(); } } return new String[0]; } /** * 刪除服務器文件 * @param remoteFileName 文件在服務器中名稱 * @author: wrh45 * @date: 2017年8月6日上午12:15:22 */ public static int deleteFile(String remoteFileName) { try { if (remoteFileName == null || "".equals(remoteFileName) || !remoteFileName.contains(groupName)) { return -1; } if (storageClient == null) { init(); } String fileURL = remoteFileName.substring(remoteFileName.indexOf(groupName)); String group = fileURL.substring(0, remoteFileName.indexOf("/") + 1); String fileName = fileURL.substring(remoteFileName.indexOf("/") + 2); int code = storageClient.delete_file(group, fileName); return code; } catch (Exception e) { e.printStackTrace(); System.out.println("The File Delete Fail"); } return -1; } /** * 獲取文件信息 * @param groupName 組名 * @param remoteFilename 遠程文件名 * @return * @author: wrh45 * @date: 2017年8月8日上午12:25:26 */ public static FileInfo getFileInfo(String groupName, String remoteFilename) { try { if (storageClient == null ) { init(); } FileInfo fileInfo = storageClient.get_file_info(groupName, remoteFilename); return fileInfo; } catch (Exception e) { e.printStackTrace(); System.out.println( "Get File Info Fail" ); } return null ; } } |
總結
以上所述是小編給大家介紹的FasfDFS整合Java實現文件上傳下載功能實例詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.cnblogs.com/immortal-ghost/p/7300185.html