使用Spring Boot集成FastDFS的示例代码

 更新时间:2018年02月01日 10:58:05   作者:纯洁的微笑  
本篇文章主要介绍了使用Spring Boot集成FastDFS的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

这篇文章我们介绍如何使用Spring Boot将文件上传到分布式文件系统FastDFS中。

这个项目会在上一个项目的基础上进行构建。

1、pom包配置

我们使用Spring Boot最新版本1.5.9、jdk使用1.8、tomcat8.0。

<dependency>
  <groupId>org.csource</groupId>
  <artifactId>fastdfs-client-java</artifactId>
  <version>1.27-SNAPSHOT</version>
</dependency>

加入了fastdfs-client-java包,用来调用FastDFS相关的API。

2、配置文件

resources目录下添加fdfs_client.conf文件

connect_timeout = 60
network_timeout = 60
charset = UTF-8
http.tracker_http_port = 8080
http.anti_steal_token = no
http.secret_key = 123456

tracker_server = 192.168.53.85:22122
tracker_server = 192.168.53.86:22122

配置文件设置了连接的超时时间,编码格式以及tracker_server地址等信息

详细内容参考:fastdfs-client-java

3、封装FastDFS上传工具类

封装FastDFSFile,文件基础信息包括文件名、内容、文件类型、作者等。

public class FastDFSFile {
  private String name;
  private byte[] content;
  private String ext;
  private String md5;
  private String author;
  //省略getter、setter

封装FastDFSClient类,包含常用的上传、下载、删除等方法。

首先在类加载的时候读取相应的配置信息,并进行初始化。

static {
  try {
    String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();;
    ClientGlobal.init(filePath);
    trackerClient = new TrackerClient();
    trackerServer = trackerClient.getConnection();
    storageServer = trackerClient.getStoreStorage(trackerServer);
  } catch (Exception e) {
    logger.error("FastDFS Client Init Fail!",e);
  }
}

文件上传

public static String[] upload(FastDFSFile file) {
  logger.info("File Name: " + file.getName() + "File Length:" + file.getContent().length);
  NameValuePair[] meta_list = new NameValuePair[1];
  meta_list[0] = new NameValuePair("author", file.getAuthor());
  long startTime = System.currentTimeMillis();
  String[] uploadResults = null;
  try {
    storageClient = new StorageClient(trackerServer, storageServer);
    uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
  } catch (IOException e) {
    logger.error("IO Exception when uploadind the file:" + file.getName(), e);
  } catch (Exception e) {
    logger.error("Non IO Exception when uploadind the file:" + file.getName(), e);
  }
  logger.info("upload_file time used:" + (System.currentTimeMillis() - startTime) + " ms");
  if (uploadResults == null) {
    logger.error("upload file fail, error code:" + storageClient.getErrorCode());
  }
  String groupName = uploadResults[0];
  String remoteFileName = uploadResults[1];
  logger.info("upload file successfully!!!" + "group_name:" + groupName + ", remoteFileName:" + " " + remoteFileName);
  return uploadResults;
}

使用FastDFS提供的客户端storageClient来进行文件上传,最后将上传结果返回。

根据groupName和文件名获取文件信息。

public static FileInfo getFile(String groupName, String remoteFileName) {
  try {
    storageClient = new StorageClient(trackerServer, storageServer);
    return storageClient.get_file_info(groupName, remoteFileName);
  } catch (IOException e) {
    logger.error("IO Exception: Get File from Fast DFS failed", e);
  } catch (Exception e) {
    logger.error("Non IO Exception: Get File from Fast DFS failed", e);
  }
  return null;
}

下载文件

public static InputStream downFile(String groupName, String remoteFileName) {
  try {
    storageClient = new StorageClient(trackerServer, storageServer);
    byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
    InputStream ins = new ByteArrayInputStream(fileByte);
    return ins;
  } catch (IOException e) {
    logger.error("IO Exception: Get File from Fast DFS failed", e);
  } catch (Exception e) {
    logger.error("Non IO Exception: Get File from Fast DFS failed", e);
  }
  return null;
}

删除文件

public static void deleteFile(String groupName, String remoteFileName)
    throws Exception {
  storageClient = new StorageClient(trackerServer, storageServer);
  int i = storageClient.delete_file(groupName, remoteFileName);
  logger.info("delete file successfully!!!" + i);
}

使用FastDFS时,直接调用FastDFSClient对应的方法即可。

4、编写上传控制类

从MultipartFile中读取文件信息,然后使用FastDFSClient将文件上传到FastDFS集群中。

public String saveFile(MultipartFile multipartFile) throws IOException {
  String[] fileAbsolutePath={};
  String fileName=multipartFile.getOriginalFilename();
  String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
  byte[] file_buff = null;
  InputStream inputStream=multipartFile.getInputStream();
  if(inputStream!=null){
    int len1 = inputStream.available();
    file_buff = new byte[len1];
    inputStream.read(file_buff);
  }
  inputStream.close();
  FastDFSFile file = new FastDFSFile(fileName, file_buff, ext);
  try {
    fileAbsolutePath = FastDFSClient.upload(file); //upload to fastdfs
  } catch (Exception e) {
    logger.error("upload file Exception!",e);
  }
  if (fileAbsolutePath==null) {
    logger.error("upload file failed,please upload again!");
  }
  String path=FastDFSClient.getTrackerUrl()+fileAbsolutePath[0]+ "/"+fileAbsolutePath[1];
  return path;
}

请求控制,调用上面方法saveFile()。

@PostMapping("/upload") //new annotation since 4.3
public String singleFileUpload(@RequestParam("file") MultipartFile file,
                RedirectAttributes redirectAttributes) {
  if (file.isEmpty()) {
    redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
    return "redirect:uploadStatus";
  }
  try {
    // Get the file and save it somewhere
    String path=saveFile(file);
    redirectAttributes.addFlashAttribute("message",
        "You successfully uploaded '" + file.getOriginalFilename() + "'");
    redirectAttributes.addFlashAttribute("path",
        "file path url '" + path + "'");
  } catch (Exception e) {
    logger.error("upload file failed",e);
  }
  return "redirect:/uploadStatus";
}

上传成功之后,将文件的路径展示到页面,效果图如下:

在浏览器中访问此Url,可以看到成功通过FastDFS展示:

这样使用Spring Boot 集成FastDFS的案例就完成了。

示例代码-github

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • java关于并发模型中的两种锁知识点详解

    java关于并发模型中的两种锁知识点详解

    在本篇文章了小编给大家整理的是一篇关于java关于并发模型中的两种锁知识点详解内容,有兴趣的朋友们可以学习下。
    2021-04-04
  • 官方详解HDFS Balancer工具主要调优参数

    官方详解HDFS Balancer工具主要调优参数

    这篇文章主要为大家介绍了HDFS Balancer工具主要调优参数的 官方详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-03-03
  • Java 数据结构中二叉树前中后序遍历非递归的具体实现详解

    Java 数据结构中二叉树前中后序遍历非递归的具体实现详解

    树是一种重要的非线性数据结构,直观地看,它是数据元素(在树中称为结点)按分支关系组织起来的结构,很象自然界中的树那样。树结构在客观世界中广泛存在,如人类社会的族谱和各种社会组织机构都可用树形象表示
    2021-11-11
  • spring boot密码加密配置与实例详解

    spring boot密码加密配置与实例详解

    BCrypt是一种专为密码哈希设计的算法,它被广泛认为是安全的选择之一,这篇文章主要介绍了spring boot密码加密配置与实例详解,需要的朋友可以参考下
    2024-12-12
  • 深入分析JAVA Synchronized关键字

    深入分析JAVA Synchronized关键字

    这篇文章主要介绍了析JAVA Synchronized关键字的相关知识,文中代码非常详细,帮助大家更好的理解和学习,感兴趣的朋友可以了解下
    2020-06-06
  • SpringBoot中的@PostConstruct注解详细解析

    SpringBoot中的@PostConstruct注解详细解析

    这篇文章主要介绍了SpringBoot中的@PostConstruct注解详细解析,@PostConstruct注解,主要用于在Spring容器启动时执行某些操作或者任务,@PostConstruct注解一般放在BEAN的方法上,一旦BEAN初始化完成之后,将会调用这个方法,需要的朋友可以参考下
    2024-01-01
  • 关于SpingMVC的<context:component-scan>包扫描踩坑记录

    关于SpingMVC的<context:component-scan>包扫描踩坑记录

    这篇文章主要介绍了关于SpingMVC的<context:component-scan>包扫描踩坑记录,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-03-03
  • Spring WebFlux实现参数校验的示例代码

    Spring WebFlux实现参数校验的示例代码

    请求参数校验,在实际的应用中很常见,网上的文章大部分提供的使用注解的方式做参数校验。本文主要介绍 Spring Webflux Function Endpoint 使用 Spring Validation 来校验请求的参数。感兴趣的可以了解一下
    2021-08-08
  • idea中maven项目模块变成灰色原因及解决方案

    idea中maven项目模块变成灰色原因及解决方案

    这篇文章主要介绍了idea中maven项目模块变成灰色原因及解决方案,文中通过图文结合的方式给大家讲解的非常详细,对大家的学习或工作有一定的帮助,需要的朋友可以参考下
    2024-03-03
  • springboot项目事务标签验证

    springboot项目事务标签验证

    本文主要介绍了springboot项目事务标签验证,文中通过示例代码介绍的非常详细,详细的介绍了不加事务标签和加事物标签的使用,需要的朋友们下面随着小编来一起学习学习吧
    2021-07-07

最新评论