FastDFSUtil.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. package com.yihu.ehr.fastdfs;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import com.fasterxml.jackson.databind.node.ObjectNode;
  4. import com.yihu.ehr.util.log.LogService;
  5. import org.csource.common.NameValuePair;
  6. import org.csource.fastdfs.*;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import java.io.InputStream;
  9. import java.net.InetSocketAddress;
  10. /**
  11. * FastDFS 客户端工具.
  12. *
  13. * 作为Bean方式来调用。
  14. *
  15. * @author szx
  16. * @author Sand
  17. */
  18. public class FastDFSUtil {
  19. public final static String GroupField = "groupName";
  20. public final static String RemoteFileField = "remoteFileName";
  21. public final static String FileIdField = "fid";
  22. public final static String FileUrlField = "fileUrl";
  23. @Autowired
  24. FastDFSClientPool clientPool;
  25. /**
  26. * 以输入流的方式上传文件
  27. * InputStream in = new FileInputStream("C://Desert.jpg");
  28. * ObjectNode msg = FileUtil.upload(in,"jpg", "沙漠");
  29. * in.close();
  30. *
  31. * @param in 输入流
  32. * @param fileExtension 文件扩展名,不要带“.”
  33. * @param description 文件名称(中文)
  34. * @return 返回值的格式如下:
  35. * {
  36. * "groupName": "healthArchiveGroup",
  37. * "remoteFileName": "/M00/00/24/rBFuH1XdQC6AP3CDAAzodQCbVVc052.jpg",
  38. * "fid": "group1/M00/00/24/rBFuH1XdQC6AP3CDAAzodQCbVVc052.jpg",
  39. * "fileURL": "http://172.19.103.13/healthArchiveGroup/M00/00/24/rBFuH1XdQC6AP3CDAAzodQCbVVc052.jpg"
  40. * }
  41. * <p>
  42. * groupName 及 remoteFileName 可以用于查询在 fastDFS 中文件的信息,如果只是图片显示,可以忽略这两个值。
  43. * fid 保存了在 fastDFS 上的完整路径,为了避免将来服务器域名发生变更,最好使用本值.服务器的域名另外配置。
  44. * fileURL 保存了完整的 web 访问路径,为了避免将来服务器域名发生变更,最好不要直接使用本值。
  45. * 如果需要在下载时,可以显示原始文件名,请在访问file_url时,增加 attname 参数,如:
  46. * <p>
  47. * http://host/healthArchiveGroup/M00/00/00/rBFuH1XdIseAUTZZAA1rIuRd3Es062.jpg?attname=a.jpg
  48. * @throws Exception
  49. */
  50. public ObjectNode upload(InputStream in, String fileExtension,String description) throws Exception {
  51. NameValuePair[] fileMetaData = new NameValuePair[1];
  52. fileMetaData[0] = new NameValuePair("description", description == null ? "" : description);
  53. return upload(in,fileExtension,fileMetaData);
  54. }
  55. /**
  56. * 以输入流的方式上传文件
  57. */
  58. public ObjectNode upload(InputStream in, String fileExtension,NameValuePair[] fileMetaData) throws Exception {
  59. StorageClient client = clientPool.getStorageClient();
  60. ObjectNode message = new ObjectMapper().createObjectNode();
  61. try {
  62. byte fileBuffer[] = new byte[in.available()];
  63. int len = 0;
  64. int temp = 0; //所有读取的内容都使用temp接收
  65. while ((temp = in.read()) != -1) { //当没有读取完时,继续读取
  66. fileBuffer[len] = (byte) temp;
  67. len++;
  68. }
  69. in.close();
  70. TrackerServer trackerServer = clientPool.getTrackerServer();
  71. String[] results = client.upload_file(fileBuffer, fileExtension, fileMetaData);
  72. if (results != null) {
  73. String fileId;
  74. int ts;
  75. String token;
  76. String fileURl;
  77. InetSocketAddress socketAddress;
  78. String groupName = results[0];
  79. String remoteFile = results[1];
  80. message.put(GroupField, groupName);
  81. message.put(RemoteFileField, remoteFile);
  82. fileId = groupName + StorageClient1.SPLIT_GROUP_NAME_AND_FILENAME_SEPERATOR + remoteFile;
  83. message.put(FileIdField, fileId);
  84. socketAddress = trackerServer.getInetSocketAddress();
  85. fileURl = "http://" + socketAddress.getAddress().getHostAddress();
  86. if (ClientGlobal.g_tracker_http_port != 80) {
  87. fileURl += ":" + ClientGlobal.g_tracker_http_port;
  88. }
  89. fileURl += "/" + fileId;
  90. if (ClientGlobal.g_anti_steal_token) {
  91. ts = (int) (System.currentTimeMillis() / 1000);
  92. token = ProtoCommon.getToken(fileId, ts, ClientGlobal.g_secret_key);
  93. fileURl += "?token=" + token + "&ts=" + ts;
  94. }
  95. message.put(FileUrlField, fileURl);
  96. LogService.getLogger(FastDFSUtil.class).info(client.get_file_info(groupName, remoteFile).toString());
  97. }
  98. } finally {
  99. clientPool.releaseStorageClient(client);
  100. }
  101. return message;
  102. }
  103. /**
  104. * 上传文件,从文件
  105. */
  106. public ObjectNode upload(String group_name, String master_filename, String prefix_name, byte[] file_buff, String file_ext_name,NameValuePair[] meta_list) throws Exception{
  107. StorageClient client = clientPool.getStorageClient();
  108. ObjectNode message = new ObjectMapper().createObjectNode();
  109. try {
  110. TrackerServer trackerServer = clientPool.getTrackerServer();
  111. String[] results = client.upload_file(group_name,master_filename,prefix_name,file_buff, file_ext_name, meta_list);
  112. if (results != null) {
  113. String fileId;
  114. int ts;
  115. String token;
  116. String fileURl;
  117. InetSocketAddress socketAddress;
  118. String groupName = results[0];
  119. String remoteFile = results[1];
  120. message.put(GroupField, groupName);
  121. message.put(RemoteFileField, remoteFile);
  122. fileId = groupName + StorageClient1.SPLIT_GROUP_NAME_AND_FILENAME_SEPERATOR + remoteFile;
  123. message.put(FileIdField, fileId);
  124. socketAddress = trackerServer.getInetSocketAddress();
  125. fileURl = "http://" + socketAddress.getAddress().getHostAddress();
  126. if (ClientGlobal.g_tracker_http_port != 80) {
  127. fileURl += ":" + ClientGlobal.g_tracker_http_port;
  128. }
  129. fileURl += "/" + fileId;
  130. if (ClientGlobal.g_anti_steal_token) {
  131. ts = (int) (System.currentTimeMillis() / 1000);
  132. token = ProtoCommon.getToken(fileId, ts, ClientGlobal.g_secret_key);
  133. fileURl += "?token=" + token + "&ts=" + ts;
  134. }
  135. message.put(FileUrlField, fileURl);
  136. System.out.print(client.get_file_info(groupName, remoteFile).toString());
  137. }
  138. } finally {
  139. clientPool.releaseStorageClient(client);
  140. }
  141. return message;
  142. }
  143. /**
  144. * 上传本地文件
  145. * ObjectNode a = FileUtil.upload("C://Desert.jpg", "沙漠");
  146. * System.out.println(a.toString());
  147. *
  148. * @param fileName 本地文件的绝对路径,如 C://Desert.jpg
  149. * @param description 文件备注, 可以为空
  150. * @return {"groupName":"group1","remoteFileName":"/M00/00/24/rBFuH1XdQC6AP3CDAAzodQCbVVc052.jpg"
  151. * {
  152. * "groupName": "healthArchiveGroup",
  153. * "remoteFileName": "/M00/00/24/rBFuH1XdQC6AP3CDAAzodQCbVVc052.jpg",
  154. * "fid": "group1/M00/00/24/rBFuH1XdQC6AP3CDAAzodQCbVVc052.jpg",
  155. * "fileURL": "http://172.19.103.13/healthArchiveGroup/M00/00/24/rBFuH1XdQC6AP3CDAAzodQCbVVc052.jpg"
  156. * }
  157. * <p>
  158. * groupName 及 remoteFileName 可以用于查询在 fastDFS 中文件的信息,如果只是图片显示,可以忽略这两个值。
  159. * fid 保存了在 fastDFS 上的完整路径,为了避免将来服务器域名发生变更,最好使用本值.服务器的域名另外配置。
  160. * fileURL 保存了完整的 web 访问路径,为了避免将来服务器域名发生变更,最好不要直接使用本值。
  161. * 如果需要在下载时,可以显示原始文件名,请在访问file_url时,增加 attname 参数,如:
  162. * <p>
  163. * http://host/healthArchiveGroup/M00/00/00/rBFuH1XdIseAUTZZAA1rIuRd3Es062.jpg?attname=a.jpg
  164. * @throws Exception
  165. */
  166. public ObjectNode upload(String fileName, String description) throws Exception {
  167. StorageClient client = clientPool.getStorageClient();
  168. try {
  169. NameValuePair[] fileMetaData;
  170. fileMetaData = new NameValuePair[1];
  171. fileMetaData[0] = new NameValuePair("description", description == null ? "" : description);
  172. // ObjectMapper objectMapper = SpringContext.getService(ObjectMapper.class);
  173. ObjectNode message = new ObjectMapper().createObjectNode();
  174. String fileExtension = "";
  175. if (fileName.contains(".")) {
  176. fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
  177. } else {
  178. throw new RuntimeException("上传失败, 文件缺失扩展名.");
  179. }
  180. TrackerServer trackerServer = clientPool.getTrackerServer();
  181. String[] results = client.upload_file(fileName, fileExtension, fileMetaData);
  182. if (results != null) {
  183. String fileId;
  184. int ts;
  185. String token;
  186. String fileUrl;
  187. InetSocketAddress inetSockAddr;
  188. String groupName = results[0];
  189. String remoteFileName = results[1];
  190. message.put(GroupField, groupName);
  191. message.put(RemoteFileField, remoteFileName);
  192. fileId = groupName + StorageClient1.SPLIT_GROUP_NAME_AND_FILENAME_SEPERATOR + remoteFileName;
  193. message.put(FileIdField, fileId);
  194. inetSockAddr = trackerServer.getInetSocketAddress();
  195. fileUrl = "http://" + inetSockAddr.getAddress().getHostAddress();
  196. if (ClientGlobal.g_tracker_http_port != 80) {
  197. fileUrl += ":" + ClientGlobal.g_tracker_http_port;
  198. }
  199. fileUrl += "/" + fileId;
  200. if (ClientGlobal.g_anti_steal_token) {
  201. ts = (int) (System.currentTimeMillis() / 1000);
  202. token = ProtoCommon.getToken(fileId, ts, ClientGlobal.g_secret_key);
  203. fileUrl += "?token=" + token + "&ts=" + ts;
  204. }
  205. message.put(FileUrlField, fileUrl);
  206. LogService.getLogger(FastDFSUtil.class).info(client.get_file_info(groupName, remoteFileName).toString());
  207. return message;
  208. } else {
  209. return null;
  210. }
  211. } finally {
  212. clientPool.releaseStorageClient(client);
  213. }
  214. }
  215. /**
  216. * 下载文件, 返回文件字节数组.
  217. *
  218. * @param groupName 在fastdfs上的卷名
  219. * @param remoteFileName 在fastdfs上的路径
  220. * @return 文件的字节码
  221. * @throws Exception
  222. */
  223. public byte[] download(String groupName, String remoteFileName) throws Exception {
  224. StorageClient client = clientPool.getStorageClient();
  225. try {
  226. byte[] b = client.download_file(groupName, remoteFileName);
  227. return b;
  228. } finally {
  229. clientPool.releaseStorageClient(client);
  230. }
  231. }
  232. /**
  233. * 下载文件到本地路径上.
  234. *
  235. * @param groupName 在 fastDFS 上的卷名
  236. * @param remoteFileName 在 fastDFS 上的路径
  237. * @param localPath 本地路径
  238. * @return 是否下载成功
  239. */
  240. public String download(String groupName, String remoteFileName, String localPath) throws Exception {
  241. StorageClient client = clientPool.getStorageClient();
  242. try {
  243. String localFileName = localPath + remoteFileName.replaceAll("/", "_");
  244. client.download_file(groupName, remoteFileName, 0, 0, localFileName);
  245. return localFileName;
  246. } finally {
  247. clientPool.releaseStorageClient(client);
  248. }
  249. }
  250. /**
  251. * 删除文件。
  252. *
  253. * @param groupName
  254. * @param remoteFileName
  255. */
  256. public void delete(String groupName, String remoteFileName) throws Exception {
  257. StorageClient client = clientPool.getStorageClient();
  258. try {
  259. client.delete_file(groupName, remoteFileName);
  260. } finally {
  261. clientPool.releaseStorageClient(client);
  262. }
  263. }
  264. }