当前位置:   article > 正文

Java实现FastDFS对文件上传、下载、删除_fastdfs java

fastdfs java

   

在一些web应用项目实施过程,会碰到这么一个问题,例如:项目中有功能需要上传图片、文件等附件,这些附件在存储时常规的情况下是存储在一个固定的目录下,在部署多个相同的Tomcat实例集群的时候,往往需要考虑这些附件的同步问题,因此采用 FastDFS来对附件进行存储管理。

FastDFS 是一个开源的分布式文件系统,她对文件进行管理,功能包括:文件存储、文件同步、文件访问(文件上传、文件下载)等,解决了大容量存储和负载均衡的问题。FastDFS的工作原理以及相关安装流程就不做过多赘述,可以搜索相关资料了解,下面就来给大家介绍一下Java如何实现通过FastDFS上传、下载、删除附件。

首先需要在项目中导入FastDFS依赖相关的Jar包,我们使用maven的情况下,如下配置:

  1. <dependency>
  2. <groupId>commons-io</groupId>
  3. <artifactId>commons-io</artifactId>
  4. <version>2.6</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>commons-fileupload</groupId>
  8. <artifactId>commons-fileupload</artifactId>
  9. <version>1.3.1</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.csource</groupId>
  13. <artifactId>fastdfs-client-java</artifactId>
  14. <version>1.29-SNAPSHOT</version>
  15. </dependency>

 

 

第二步,在springboot项目中创建配置文件fdfs_client.conf

  1. #默认值为30s
  2. connect_timeout = 10
  3. #默认值为30s
  4. network_timeout = 30
  5. charset = UTF-8
  6. http.tracker_http_port = 8080
  7. # token 防盗链功能
  8. http.anti_steal_token = true
  9. #防盗链key
  10. http.secret_key = ZFnWLBqrX3
  11. #服务器
  12. tracker_server = 127.0.0.1:22122

第三步,创建一个实体类,定义附件相关的对象

  1. public class FastDFSFile {
  2. private String name;//文件名
  3. private byte[] content; //文件的内容,字节数组
  4. private String ext; //文件扩展名,不包含(.)
  5. private String md5; //加密
  6. public FastDFSFile() {
  7. }
  8. public FastDFSFile(String name, byte[] content, String ext) {
  9. this.name = name;
  10. this.content = content;
  11. this.ext = ext;
  12. }
  13. public String getName() {
  14. return name;
  15. }
  16. public void setName(String name) {
  17. this.name = name;
  18. }
  19. public byte[] getContent() {
  20. return content;
  21. }
  22. public void setContent(byte[] content) {
  23. this.content = content;
  24. }
  25. public String getExt() {
  26. return ext;
  27. }
  28. public void setExt(String ext) {
  29. this.ext = ext;
  30. }
  31. public String getMd5() {
  32. return md5;
  33. }
  34. public void setMd5(String md5) {
  35. this.md5 = md5;
  36. }
  37. public String getAuthor() {
  38. return author;
  39. }
  40. public void setAuthor(String author) {
  41. this.author = author;
  42. }
  43. }

 

第四步,创建工具类,写入相关方法

  1. public class FastDFSClient {
  2. private final static Logger logger = LoggerFactory.getLogger(FastDFSClient.class);
  3. //初始化
  4. static {
  5. try {
  6. String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
  7. IniFileReader iniReader = new IniFileReader(filePath);
  8. String[] szTrackerServers = iniReader.getValues("tracker_server");
  9. ClientGlobal.init(filePath);
  10. } catch (Exception e) {
  11. throw new MyException(ResultEnum.FAST_DFS_ERROR);
  12. }
  13. }
  14. //上传
  15. public static String upload(FastDFSFile file){
  16. NameValuePair[] meta_list = new NameValuePair[1];
  17. meta_list[0] = new NameValuePair("author", file.getAuthor());
  18. long startTime = System.currentTimeMillis();
  19. String[] uploadResults = null;
  20. StorageClient storageClient=null;
  21. try {
  22. storageClient = getTrackerClient();
  23. //upload_file()三个参数:@param fileContent ①:文件的内容,字节数组 ②:文件扩展名 ③文件扩展信息 数组
  24. uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
  25. }catch (Exception e){
  26. e.printStackTrace();
  27. throw new MyException(ResultEnum.FAST_DFS_ERROR);
  28. }
  29. if (uploadResults == null && storageClient!=null) {
  30. logger.error("upload file fail, error code:" + storageClient.getErrorCode());
  31. }
  32. logger.info("upload_file time used:" + (System.currentTimeMillis() - startTime) + " ms");
  33. String groupName = uploadResults[0];
  34. String remoteFileName = uploadResults[1];
  35. return groupName+"/"+remoteFileName;
  36. }
  37. //下载文件
  38. public static boolean downloadFile(String localFilename, String groupName, String remoteFilename) {
  39. //localFilename 本地文件名
  40. //groupName 文件在FastDFS中的组名
  41. //remoteFilename 文件在FastDFS中的名称
  42. File file = new File(localFilename);
  43. if(!file.exists()) {
  44. if(!file.getParentFile().exists()){
  45. file.getParentFile().mkdirs();
  46. }
  47. try {
  48. file.createNewFile();
  49. } catch (IOException e) {
  50. e.printStackTrace();
  51. }
  52. }else if(file.length()>0){
  53. logger.info("file.length()="+file.length());
  54. return true;
  55. }
  56. TrackerServer trackerServer;
  57. TrackerClient trackerClient=new TrackerClient();
  58. StorageServer storageServer=null;
  59. StorageClient storageClient=null;
  60. try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
  61. trackerServer = trackerClient.getTrackerServer();
  62. storageServer=trackerClient.getStoreStorage(trackerServer);
  63. storageClient= new StorageClient(trackerServer, storageServer);
  64. byte[] content = storageClient.download_file(groupName, remoteFilename);
  65. if (content == null || content.length == 0) {
  66. boolean flag = file.delete();
  67. return false;
  68. }
  69. bos.write(content);
  70. return true;
  71. } catch (IOException | MyException e) {
  72. e.printStackTrace();
  73. return false;
  74. }catch (Exception e){
  75. e.printStackTrace();
  76. return false;
  77. }
  78. }
  79. //删除
  80. public static int deleteFile(String groupName, String remoteFileName) throws Exception {
  81. //remoteFileName--文件路径 例如:M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg
  82. //groupName --文件路径,例如:group1/M00/00/00/wKgRsVjtwpSAXGwkAAAweEAzRjw471.jpg中的group1
  83. StorageClient storageClient = getTrackerClient();
  84. return storageClient.delete_file(groupName, remoteFileName);
  85. }
  86. //查询文件信息
  87. public static FileInfo getFile(String groupName, String remoteFileName) {
  88. try {
  89. StorageClient storageClient = getTrackerClient();
  90. return storageClient.get_file_info(groupName, remoteFileName);
  91. } catch (IOException e) {
  92. logger.error("IO Exception: Get File from Fast DFS failed", e);
  93. } catch (Exception e) {
  94. logger.error("Non IO Exception: Get File from Fast DFS failed", e);
  95. }
  96. return null;
  97. }
  98. }
 

 

第五步,调用示例

  1. public class UploadDFS {
  2. //上传文件
  3. public static String saveFile(MultipartFile multipartFile) throws IOException {
  4. String fileName=multipartFile.getOriginalFilename();
  5. String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
  6. byte[] file_buff = null;
  7. InputStream inputStream=multipartFile.getInputStream();
  8. if(inputStream!=null){
  9. int len1 = inputStream.available();
  10. file_buff = new byte[len1];
  11. inputStream.read(file_buff);
  12. }
  13. inputStream.close();
  14. FastDFSFile file = new FastDFSFile(fileName, file_buff, ext);
  15. return FastDFSClient.upload(file);
  16. }
  17. //下载
  18. public static boolean downFile(String localFilename, String groupName, String remoteFilename){
  19. //下载完成后到存储路径找下载的文件 localFilename
  20. return FastDFSClient.downloadFile(localFilename,groupName,remoteFilename);
  21. }
  22. //删除
  23. public static void deleteFile(String groupName, String remoteFileName){
  24. try {
  25. int res= FastDFSClient.deleteFile(groupName,remoteFileName);
  26. } catch (Exception e) {
  27. throw new RuntimeException(e);
  28. }
  29. }
  30. }

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号