前言

对FastDFS文件系统安装后的使用。

FastDFS的安装请参考这篇:Docker中搭建FastDFS文件系统(多图)

本文环境:IDEA + JDK1.8 + Maven

本文项目代码:https://niceyoo.lanzous.com/iFF6Ng8h55g

1、引入依赖

简单说一下这个依赖部分,目前大部分都是采用的如下依赖:

  1. <!-- https://mvnrepository.com/artifact/net.oschina.zcx7878/fastdfs-client-java -->
    <dependency>
        <groupId>net.oschina.zcx7878</groupId>
        <artifactId>fastdfs-client-java</artifactId>
        <version>1.27.0.0</version>
    </dependency>

本着不重复造轮子,且为了使用方便我们可以去GitHub找一个集成好的依赖:

https://github.com/tobato/FastDFS_Client

  1. <dependency>
        <groupId>com.github.tobato</groupId>
        <artifactId>fastdfs-client</artifactId>
        <version>1.27.2</version>
    </dependency>

2、将Fdfs配置引入项目

只需要创建一个配置类就可以了:

  1. @Configuration
    @Import(FdfsClientConfig.class)
    @EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
    public class ComponetImport {
        // 导入依赖组件
    }

参考截图:

3、在application.yml当中配置Fdfs相关参数

根据自己情况修改相应ip地址及端口号:

  1. server:
      port: 8080

    ip: 10.211.55.4 # 根据自己FastDFS服务器修改

    fdfs:
      so-timeout: 1501
      connect-timeout: 601
      thumb-image:             #缩略图生成参数
        width: 150
        height: 150
      tracker-list:            #TrackerList参数,支持多个
        - 10.211.55.4:22122
      web-server-url: http://${ip}:8888/

4、client封装工具类

创建FastDFSClient.java包装工具类,方便后面使用:

  1. import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
    import com.github.tobato.fastdfs.domain.fdfs.StorePath;
    import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
    import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
    import com.github.tobato.fastdfs.service.FastFileStorageClient;
    import org.apache.commons.io.FilenameUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import org.springframework.web.multipart.MultipartFile;
    import java.io.ByteArrayInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.nio.charset.Charset;

    @Component
    public class FastDFSClient {

        @Autowired
        private FastFileStorageClient storageClient;

        @Autowired
        private FdfsWebServer fdfsWebServer;

        /**
         * 上传文件
         * @param file 文件对象
         * @return 文件访问地址
         * @throws IOException
         */
        public String uploadFile(MultipartFile file) throws IOException {
            StorePath storePath = storageClient.uploadFile(file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null);
            return getResAccessUrl(storePath);
        }

        /**
         * 上传文件
         * @param file 文件对象
         * @return 文件访问地址
         * @throws IOException
         */
        public String uploadFile(File file) throws IOException {
            FileInputStream inputStream = new FileInputStream (file);
            StorePath storePath = storageClient.uploadFile(inputStream,file.length(), FilenameUtils.getExtension(file.getName()),null);
            return getResAccessUrl(storePath);
        }

        /**
         * 将一段字符串生成一个文件上传
         * @param content 文件内容
         * @param fileExtension
         * @return
         */
        public String uploadFile(String content, String fileExtension) {
            byte[] buff = content.getBytes(Charset.forName("UTF-8"));
            ByteArrayInputStream stream = new ByteArrayInputStream(buff);
            StorePath storePath = storageClient.uploadFile(stream,buff.length, fileExtension,null);
            return getResAccessUrl(storePath);
        }

        /**
         * 封装图片完整URL地址
          */
        private String getResAccessUrl(StorePath storePath) {
            String fileUrl = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
            return fileUrl;
        }

        /**
         * 删除文件
         * @param fileUrl 文件访问地址
         * @return
         */
        public void deleteFile(String fileUrl) {
            if (StringUtils.isEmpty(fileUrl)) {
                return;
            }
            try {
                StorePath storePath = StorePath.parseFromUrl(fileUrl);
                storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
            } catch (FdfsUnsupportStorePathException e) {
                System.out.println(e.getMessage());
                /** TODO 只是测试,所以未使用,logger,正式环境请修改打印方式 **/
            }
        }
        /**
         * 下载文件
         *
         * @param fileUrl 文件URL
         * @return 文件字节
         * @throws IOException
         */
        public byte[] downloadFile(String fileUrl) throws IOException {
            String group = fileUrl.substring(0, fileUrl.indexOf("/"));
            String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
            DownloadByteArray downloadByteArray = new DownloadByteArray();
            byte[] bytes = storageClient.downloadFile(group, path, downloadByteArray);
            return bytes;
        }

    }

5、创建Conttoler测试类

5.1 文件上传测试
  1. @RestController
    @RequestMapping("/file")
    public class FileUploadController {

        @Autowired
        private FastDFSClient fastDFSClient;

        /**
         * 上传
         * @param file
         * @return
         * @throws IOException
         */
        @RequestMapping("/upload")
        public String uploadFile(MultipartFile file) throws IOException {
            return fastDFSClient.uploadFile(file);
        }

    }

执行效果截图:

5.2、下载文件测试

  1. @RestController
    @RequestMapping("/file")
    public class FileUploadController {

        @Autowired
        private FastDFSClient fastDFSClient;

        /**
         * 下载
         * @param fileUrl
         * @param response
         * @throws IOException
         */
        @RequestMapping("/download")
        public void downloadFile(String fileUrl, HttpServletResponse response) throws IOException {
            byte[] bytes = fastDFSClient.downloadFile(fileUrl);
            /** TODO 这里只是为了整合fastdfs,所以写死了文件格式。需要在上传的时候保存文件名。下载的时候使用对应的格式 **/
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("sb.xlsx", "UTF-8"));
            response.setCharacterEncoding("UTF-8");
            ServletOutputStream outputStream = null;
            try {
                outputStream = response.getOutputStream();
                outputStream.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

测试下载路径:

http://127.0.0.1:8080/file/download?fileUrl=group1/M00/00/00/CtM3BF84r4SAEPDgAABoGL78QcY682.jpg

拼接的参数为:group1/M00/00/00/CtM3BF84r4SAEPDgAABoGL78QcY682.jpg

大家想修改路径的话,需要同步修改 downloadFile() 方法里的分隔方式。

你知道的越多,不知道的就越多,欢迎关注我的微信公众号:niceyoo

SpringBoot集成FastDFS依赖实现文件上传的更多相关文章

  1. SpringBoot --web 应用开发之文件上传

    原文出处: oKong 前言 上一章节,我们讲解了利用模版引擎实现前端页面渲染,从而实现动态网页的功能,同时也提出了兼容jsp项目的解决方案.既然开始讲解web开发了,我们就接着继续往web这个方向继 ...

  2. SpringBoot整合阿里云OSS文件上传、下载、查看、删除

    1. 开发前准备 1.1 前置知识 java基础以及SpringBoot简单基础知识即可. 1.2 环境参数 开发工具:IDEA 基础环境:Maven+JDK8 所用技术:SpringBoot.lom ...

  3. springBoot(3)---目录结构,文件上传

    目录结构,文件上传 一.目录结构 1.目录讲解 src/main/java:存放代码      src/main/resources                   static: 存放静态文件, ...

  4. 七、springBoot 简单优雅是实现文件上传和下载

    前言 好久没有更新spring Boot 这个项目了.最近看了一下docker 的知识,后期打算将spring boot 和docker 结合起来.刚好最近有一个上传文件的工作呢,刚好就想起这个脚手架 ...

  5. SpringBoot整合Fastdfs,实现图片上传(IDEA)

    我们部署Fastdfs,就是为了实现文件的上传. 现在使用idea整合Fastdfs,实现图片上传 部署环境:Centos7部署分布式文件存储(Fastdfs) 利用Java客户端调用FastDFS ...

  6. springboot中使用分页,文件上传,jquery的具体步骤(持续更新)

    分页: pom.xml     加依赖 <dependency> <groupId>com.github.pagehelper</groupId> <arti ...

  7. [二十]SpringBoot 之 (多)文件上传

    (1)新建maven Java project 新建一个名称为spring-boot-fileuploadmaven java项目 (2)在pom.xml加入相应依赖: <project xml ...

  8. SpringBoot整合FastDFS实现图片的上传

     文件的上传和预览在web开发领域是随处可见,存储的方式有很多,本文采用阿里巴巴余庆大神开发的FastDFS进行文件的存储,FastDFS是一个分布式文件存储系统,可以看我上一篇博文,有安装和配置教程 ...

  9. SpringBoot从入门到精通十一(SpringBoot文件上传的两种方法)

    前言 在企业级项目开发过程中,上传文件是最常用到的功能.SpringBoot集成了SpringMVC,当然上传文件的方式跟SpringMVC没有什么出入. 本章目标 使用SpringBoot项目完成单 ...

随机推荐

  1. pip install kaggle 出现 【网络不可达】?

    解决办法: pip install kaggle -i http://pypi.douban.com/simple --trusted-host pypi.douban.com

  2. 【Luogu】P2292 [HNOI2004]L语言 题解

    前置芝士:\(Trie\)字典树 这道题,说是AC自动机,实际上一个\(Trie+\)队列轻松搞定. 首先,我们对所有单词建一棵\(Trie\). 然后,定义一个空队列\(Q\),初始时把\(-1\) ...

  3. C语言经典100例-ex002

    系列文章<C语言经典100例>持续创作中,欢迎大家的关注和支持. 喜欢的同学记得点赞.转发.收藏哦- 后续C语言经典100例将会以pdf和代码的形式发放到公众号 欢迎关注:计算广告生态 即 ...

  4. 力扣 122 买卖股票的最佳时机II

    力扣 122 买卖股票的最佳时机II 思路: 动态规划,表面上是\(O(2^n)\)的搜索空间,实际上该天的选择只与前一天的状态(是否持有股票)有关.从收益的角度来看,确实每一天的不同选择都会产生不同 ...

  5. SpringBoot入门最简单的一个项目示例

    使用IDEA创建一个SpringBoot项目 1.1 打开IDEA,文件-New-Project 1.2下一步,选择版本8(根据自己安装的JDK版本来选择) 1.3 下一步后点击Web,勾选Sprin ...

  6. java小工具,使用Swing展示左树右表结构

    代码直接上: 入口类 import java.io.File; import java.util.ArrayList; import java.util.List; import org.json.J ...

  7. JavaScript变量污染

    定义过多的全局变量,有可能造成全局变量冲突,这种现象称为变量污染. 全局变量在全局作用域内外都是可见的.若是已经声明了一个全局变量,再以相同的关键字和标识符重新声明全局变量,后者的赋值会替代前者的赋值 ...

  8. Tim Urban:如何选择真正适合你的职业?

    Wait But Why是一个专注于写长博客的网站,Tim Urban是网站的创始人之一.Tim Urban专注于写长论文,与时下的轻度阅读完全背道而驰,文章动辄几千甚至上万字,但令人吃惊的是却拥有惊 ...

  9. Servlet与通信协议概述

    Servlet 是一个java应用程序,一个Servlet应用有一个或多个Servlet程序,JSP页面会被转换和编译成Servlet程序. Servlet应用无法独立运行,必须运行在Servlet容 ...

  10. http 请求体数据--ngx

    HTTP包体的长度有可能非常大,不同业务可能对包体读取 处理不相同, 比如waf, 也许会读取body内容或者只是读取很少的前几十字节.所以根据不同业务特性,对http body 数据包处理方式不同, ...