springboot(十八):使用springboot集成fastdfs

整合侠      2022-04-25     504

关键词:

Spring Boot(十八):使用Spring Boot集成FastDFS

环境:Spring Boot最新版本1.5.9、jdk使用1.8、tomcat8.0

功能:使用Spring Boot将文件上传到分布式文件系统FastDFS中。

一、pom包配置

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

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

二、配置文件

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上传工具类

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

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

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

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

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);
    }
}

(3)文件上传:

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;
}

(4)下载文件:

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;
}

(5)删除文件:

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对应的方法即可。

四、编写上传控制类

从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展示:

 

java框架技术之十八节springboot课件上手教程(代码片段)

学习目标了解SpringBoot的作用掌握java配置的方式了解SpringBoot自动配置原理掌握SpringBoot的基本使用了解Thymeleaf的基本使用1.了解SpringBoot在这一部分,我们主要了解以下3个问题:什么是SpringBoot为什么要学习SpringBootSpringBoot的... 查看详情

java框架技术之十八节springboot课件上手教程(代码片段)

学习目标了解SpringBoot的作用掌握java配置的方式了解SpringBoot自动配置原理掌握SpringBoot的基本使用了解Thymeleaf的基本使用1.了解SpringBoot在这一部分,我们主要了解以下3个问题:什么是SpringBoot为什么要学习SpringBootSpringBoot的... 查看详情

springboot常用注解

@SpringBootApplication:??包含@Configuration、@EnableAutoConfiguration、@ComponentScan通常用在主类上。??很多SpringBoot开发者总是使用@Configuration,@EnableAutoConfiguration和@ComponentScan注解他们的main类。由于这些注解被如此频繁地一块使用,SpringBo 查看详情

(转)springboot

(二期)4、springboot的综合讲解【课程四】springbo...概念.xmind64.5KB【课程四】spring装配方式.xmind0.2MB【课程四预习】spri...解读.xmind0.1MB【课程四】springbo...过程.xmind0.3MB  gitdemo:https://gitee.com/lv-success/git-second/tree/ma 查看详情

第十八章springboot+thymeleaf

代码结构:1、ThymeleafControllerpackagecom.xxx.firstboot.web;importorg.springframework.stereotype.Controller;importorg.springframework.ui.Model;importorg.springframework.web.bind.annotation.RequestMapping;i 查看详情

springboot基本概念

1.1什么是springbootSpringBoot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。使用SpringBoot很容... 查看详情

springboot(十八)@value@import@importresource@propertysource

SpringBoot提倡基于Java的配置。这两篇博文主要介绍springboot一些常用的注解介绍v@value通过@Value可以将外部的值动态注入到Bean中。添加application.properties的属性,方便后面演示。domain.name=cnblogs@Value("字符串1")privateStringtestName;//注入普... 查看详情

springbootspringboot缓存(十八)

  本章介绍SpringBoot的缓存机制及使用Spring缓存介绍  Spring从3.1开始定义了org.springframework.cache.Cache和org.springframework.cache.CacheManager接口来统一不同的缓存技术;并支持使用JCache(JSR-107)注解简化我们开发;  •Cache接口为缓存... 查看详情

springboot技术优点

  一、SpringBoot的优势,使用它跟之前的对比,有什么改进。  1、什么是SpringBoot  答:Springboot是一个快速整合第三方框架,简化xml,内置Http服务器也就是之前所用Tomcat服务器  2、Springboot和ssm、ssh框架区别  答... 查看详情

springboot入门知识

SpringBoot简介SpringBoot是由Pivotal[?p?v?tl]团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,SpringBoo... 查看详情

springboot1.5.4集成swagger2构建restfulapi(十八)

上一篇博客地址:springboot1.5.4整合rabbitMQ(十七)1      SpringBoot集成Swagger2构建RESTfulAPI文档1.1 Swagger2简介Swagger2官网:http://swagger.io/由于SpringBoot能够快速开发、便捷部署等特性,相信有很大一部分SpringBoo 查看详情

第二十八章springboot+zipkin(brave定制-asynchttpclient)

brave本身没有对AsyncHttpClient提供类似于brave-okhttp的ClientRequestInterceptor和ClientResponseInterceptor,所以需要我们定制,而ServerRequestInterceptor和ServerResponseInterceptor是在BraveServletFilter部分直接指定就好了(这在任何client技术下都可以 查看详情

springboot2系列教程(十八)|整合mongodb

...,请后台留言,反正我也不会听。前言如题,今天介绍下SpringBoot是如何整合MongoDB的。MongoDB简介MongoDB是由C++编写的非关系型数据库,是一个基于分布式文件存储的开源数据库系统,它将数据存储为一个文档,数据结构由键值(key=... 查看详情

十八springboot2核心技术——整合redis(代码片段)

SpringBoot集成Redis1.1、目标完善根据学生id查询学生总数的功能,先从redis缓存中查找,如果找不到,再从数据库中查找,然后放到redis缓存中。1.2、实现步骤1.2.1、在pom.xml文件中添加redis依赖<dependencies><!--Sprin... 查看详情

十八springboot2核心技术——整合redis(代码片段)

SpringBoot集成Redis1.1、目标完善根据学生id查询学生总数的功能,先从redis缓存中查找,如果找不到,再从数据库中查找,然后放到redis缓存中。1.2、实现步骤1.2.1、在pom.xml文件中添加redis依赖<dependencies><!--Sprin... 查看详情

springboot整合mongodb

...自己大概整理了下,项目中的相关配置就不叙述了,由于springboot的快捷开发方式,所以springboot项目中要使用Mongodb,只需要添加依赖和配置application.properties文件即可。整和方式一共有两种,一种是JPA的快捷方式,还有一种是实... 查看详情

springboot入门demo(代码片段)

...等这里不做介绍,不会的小伙伴可以百度一下)3.jdk1.84.SpringBoot2.1.5二.构建SpringBoot项目1.使用maven构建SpringBoot项目第一次创建项目时,会花费好长时间去下载SpringBoot2.1.5相关的jar包,需要耐心等待2.SpringBoot启动器所谓的springBo 查看详情

使用springboot+druid+mybatisplus完成多数据源配置

一.简介 1.版本    springboot版本为2.0.3.RELEASE,mybatisplus版本为2.1.9,druid版本为1.1.9,swagger版本为2.7.0 2.项目地址   https://gitee.com/hsbt2333/ssm.git 3.留个记录,方便查找    开发步骤:    1.新建spri... 查看详情