JAVA上传文件到FastDFS(SpringBoot)

一起探讨学习

欢迎大家进群,一起讨论学习

每天给大家提供技术干货

在这里插入图片描述

博主技术笔记 https://notes.xiyankt.com


博主开源微服架构前后端分离技术博客项目源码地址,欢迎各位star https://gitee.com/bright-boy/xiyan-blog


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

上篇文件介绍了如何使用docker搭建FastDFS,如没有搭建的请参考这篇文章

maven依赖

<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: 192.168.28.128 # 根据自己FastDFS服务器修改

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

4、client封装工具类

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测试类

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

}

执行效果截图:
在这里插入图片描述
在这里插入图片描述

下载文件测试

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

在这里插入图片描述

注意上传大文件nginx需要做如下配置

找到自己主机的nginx.conf配置文件,打开
在http{}中加入
    #客户端文件上传的大小
    client_max_body_size 500m;
    #用于tomcat反向代理,解决nginx 504错误 
    proxy_connect_timeout 300; #单位秒 
    proxy_send_timeout 300; #单位秒 
    proxy_read_timeout 300; #单位秒 
    proxy_buffer_size 16k; 
    proxy_buffers 4 64k; 
    proxy_busy_buffers_size 128k; 
    proxy_temp_file_write_size 128k;
    # ps:以timeout结尾配置项时间要配置大点
然后重启nginx

各位老哥关注下呗

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
### 回答1: 好的,关于Spring Boot和FastDFS的问题,我可以帮助您回答。 Spring Boot是一种用于快速开发Spring应用程序的框架,它使开发者可以更快地构建和部署应用程序,而不需要太多的配置和样板代码。而FastDFS则是一种分布式文件系统,它提供了高可靠性和高性能的文件存储和访问服务,可以用于存储大型文件。 在Spring Boot应用程序中使用FastDFS,您可以使用FastDFS客户端库,例如FastDFS Java客户端。该库提供了一组API,可以与FastDFS服务器进行交互,以实现文件上传、下载和删除等功能。您可以在Spring Boot应用程序中添加该库的依赖项,并使用其API来处理文件操作。 在使用FastDFS时,您需要先配置FastDFS服务器的地址和端口,以便客户端库可以连接到服务器。然后,您可以使用客户端库的API来上传文件FastDFS服务器,获取文件的URL或者删除文件等操作。 总的来说,使用Spring Boot和FastDFS可以快速、高效地实现文件存储和访问的功能。希望这个回答对您有所帮助。 ### 回答2: Spring Boot 是一个基于 Spring Framework 的快速开发框架,它通过提供快速、可选其他功能并且非常干净的开发方式,加速了 Spring 平台的开发过程。而 FastDFS 是一个开源的轻量级分布式文件系统,它以文件作为存储对象,实现了文件的存储、访问和管理功能。 SpringBoot FastDFSSpring Boot 与 FastDFS 结合起来,使得在基于 Spring Boot 的 Web 应用中使用 FastDFS 更加高效、简单方便。SpringBoot FastDFS 框架提供了一些简单易用、高效的工具类和方法,可以快速地将文件上传到 FastDFS 中,并且可以实现文件的快速下载、删除等操作,可以大大提升开发效率。 SpringBoot FastDFS 框架的使用非常简单,只需要在项目中添加所需依赖后,创建一个 FastDFS 的客户端,并配置相应的 FastDFS 服务器的地址、端口等信息即可,然后就可以快速的上传、下载、删除文件了。通过SpringBoot FastDFS 框架,我们可以将文件存储功能集成到我们的 Web 应用中,省去了自己编写上传、下载文件相关的代码的麻烦,极大地提高了开发效率。 总之,SpringBoot FastDFS 给我们带来了高效、简单、便捷的文件存储解决方案,无论是对于小型应用还是大型企业应用,都具有非常广泛的应用价值。 ### 回答3: SpringBoot是一个基于Spring框架开发的快速构建应用程序的工具,为开发者提供了快速的开发环境和自动化配置,让开发者可以更专注于业务逻辑的实现。FastDFS是一个开源的分布式文件系统,具有高可靠性、高性能、高扩展性和容错性等优点。SpringBoot集成FastDFS可以让我们更加方便地进行文件上传与管理。下面,我们将介绍如何使用SpringBootFastDFS进行文件上传和下载。 1、添加FastDFS依赖 首先,在SpringBoot工程中添加FastDFS的依赖。可以通过在pom.xml文件中添加以下代码实现: ``` <!-- 引入FastDFS的依赖 --> <dependency> <groupId>com.github.tobato</groupId> <artifactId>fastdfs-client</artifactId> <version>1.27.2</version> </dependency> ``` 2、配置FastDFS连接信息 在SpringBoot工程中,需要在application.yml或application.properties中配置FastDFS的连接信息,如下: ``` # FastDFS配置 fdfs: # FastDFS服务地址 tracker-list: 192.168.0.1:22122 # FastDFS存储基础路径 storage-base-path: /data # FastDFS http访问路径 storage-http-port: 80 storage-http-prefix: http://192.168.0.1 ``` 3、创建FastDFS服务 通过在SpringBoot工程中创建FastDFS服务类,实现FastDFS文件上传和下载的功能: ``` @Service public class FastDFSService { @Autowired private FastFileStorageClient storageClient; /** * 上传文件 * * @param file 文件 * @return 文件路径 * @throws IOException IO异常 */ public String upload(MultipartFile file) throws IOException { StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null); return storePath.getFullPath(); } /** * 下载文件 * * @param fileUrl 文件路径 * @return 文件内容 * @throws IOException IO异常 */ public byte[] download(String fileUrl) throws IOException { String group = fileUrl.substring(0, fileUrl.indexOf("/")); String path = fileUrl.substring(fileUrl.indexOf("/") + 1); return storageClient.downloadFile(group, path, new DownloadByteArray()); } } ``` 以上就是SpringBoot集成FastDFS的基本使用方法。使用SpringBootFastDFS进行文件上传和下载,可以大大简化开发过程,提高开发效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘明同学呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值