SpringBoot集成FastDFS依赖实现文件上传的示例

 更新时间:2021年05月11日 14:36:14   作者:niceyoo  
这篇文章主要介绍了SpringBoot集成FastDFS依赖实现文件上传,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

前言

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

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

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

本文项目代码:fastdfs_jb51.rar

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

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

2、将Fdfs配置引入项目

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

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

参考截图:

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

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

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包装工具类,方便后面使用:

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 文件上传测试

@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、下载文件测试

@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() 方法里的分隔方式。

到此这篇关于SpringBoot集成FastDFS依赖实现文件上传的示例的文章就介绍到这了,更多相关SpringBoot FastDFS文件上传内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 浅谈三分钟学习Java泛型中T、E、K、V、?的含义

    浅谈三分钟学习Java泛型中T、E、K、V、?的含义

    这篇文章主要介绍了浅谈三分钟学习Java泛型中T、E、K、V、?的含义,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-12-12
  • 浅谈Spring Cloud zuul http请求转发原理

    浅谈Spring Cloud zuul http请求转发原理

    这篇文章主要介绍了浅谈Spring Cloud zuul http请求转发原理,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-08-08
  • JAVA提高第七篇 类加载器解析

    JAVA提高第七篇 类加载器解析

    这篇文章主要为大家详细介绍了JAVA提高第七篇类加载器的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-10-10
  • Java的ThreadContext类加载器的实现

    Java的ThreadContext类加载器的实现

    这篇文章主要介绍了Java的ThreadContext类加载器的实现,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-06-06
  • IntelliJ IDEA中显示和关闭工具栏与目录栏的方法

    IntelliJ IDEA中显示和关闭工具栏与目录栏的方法

    今天小编就为大家分享一篇关于IntelliJ IDEA中显示和关闭工具栏与目录栏的方法,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2018-10-10
  • Spring Security短信验证码实现详解

    Spring Security短信验证码实现详解

    本文主要介绍了Spring Security短信验证码的实现详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-11-11
  • Java去除字符串空格的几种方法简单举例

    Java去除字符串空格的几种方法简单举例

    在Java中要去掉字符串中的空格,可以使用多种方法,这篇文章主要给大家介绍了关于Java去除字符串空格的几种方法,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2023-12-12
  • springboot 文件上传大小配置的方法

    springboot 文件上传大小配置的方法

    本篇文章主要介绍了springboot 文件上传大小配置的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • Springboot+Bootstrap实现增删改查实战

    Springboot+Bootstrap实现增删改查实战

    这篇文章主要介绍了Springboot+Bootstrap实现增删改查实战,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12
  • Java中BigDecimal的加减乘除、比较大小与使用注意事项

    Java中BigDecimal的加减乘除、比较大小与使用注意事项

    对于不需要任何准确计算精度的数字可以直接使用float或double,但是如果需要精确计算的结果,则必须使用BigDecimal类,而且使用BigDecimal类也可以进行大数的操作,下面这篇文章给大家介绍了Java中BigDecimal的加减乘除、比较大小与使用注意事项,需要的朋友可以参考下。
    2017-11-11

最新评论