fastdfs结合springboot使用

文章详细介绍了如何在Java应用中配置FastDFS客户端,包括POM依赖、YAML配置文件,以及设置上传、下载和删除文件的方法。服务层展示了如何处理MultipartFile对象,校验文件内容,上传图片到FastDFS,并生成缩略图。同时,文章还包含了文件下载和删除的示例代码。
摘要由CSDN通过智能技术生成

pom依赖

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

yaml文件

# 分布式文件系统FDFS配置
fdfs:
  so-timeout: 1500 # 读取时间
  connect-timeout: 600 # 连接超时时间
  thumb-image: #缩略图生成参数
    width: 150
    height: 150
  tracker-list: #Tracker服务配置地址列表
  - 192.168.3.10:22122
  - 192.168.3.12:22122
  - 192.168.3.13:22122
  pool:
    #从池中借出的对象的最大数目(配置为-1表示不限制)
    max-total: -1
    #获取连接时的最大等待毫秒数(默认配置为5)
    max-wait-millis: 5000
    #每个key最大连接数
    max-total-per-key: 50
    #每个key对应的连接池最大空闲连接数
    max-idle-per-key: 10
   #每个key对应的连接池最小空闲连接数
   min-idle-per-key: 5

upload:
  base-url: http://fastdfs.com:8888/

添加Config配置

@Configuration
public class FileConfig {
/**
* 解决上传文件过大导致异常的问题。
* the request was rejected because its size (170982031) exceeds the
configured
* @return
*/
	@Bean
	public MultipartConfigElement multipartConfigElement() {
	MultipartConfigFactory factory = new MultipartConfigFactory();
	factory.setMaxRequestSize(DataSize.ofBytes(200*1048576L));
	factory.setMaxFileSize(DataSize.ofBytes(200*1048576L));
	return factory.createMultipartConfig();
	}
}

service层

	@Autowired
    private FastFileStorageClient fastFileStorageClient;
    @Value("${upload.base-url}")
    private String baseUrl;
    /**
     * 上传图片
     * @param file
     * @return
     */
    public String uploadImage(MultipartFile file) {
        try {
            //校验文件
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null || image.getWidth() == 0 || image.getHeight() ==
                    0) {
                throw new RuntimeException("上传文件不是图片");
            }
        } catch (IOException e) {
            log.error("校验文件内容失败....{}", e);
            throw new RuntimeException("校验文件内容失败" + e.getMessage());
        }
        try {
            // 获取扩展名
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
//            String filename = UUID.randomUUID().toString();
//            File baseUrlFile = new File(baseUrl);
//            if (!baseUrlFile.exists()) baseUrlFile.mkdirs();
//            File newfile = new File(baseUrlFile, filename+"."+extension);
//            FileInputStream fileInputStream = new FileInputStream(newfile);

            //上传略缩图
            //StorePath storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(file.getInputStream(),
                            file.getSize(), extension, null);
            // 上传到FastDFS
            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(),
                            extension, null);
            // 返回路径
            return baseUrl+storePath.getFullPath();
        } catch (IOException e) {
            log.error("【文件上传】上传文件失败!....{}", e);
            throw new RuntimeException("【文件上传】上传文件失败!" +
                    e.getMessage());
        }
    }

文件下载

	try {
			byte[] bytes = fastFileStorageClient.downloadFile("group1",
					"M00/00/00/wKgDDGDub22AO4HUAApS0I7eS2U644_150x150.jpg", new
							DownloadByteArray());
			FileOutputStream stream = new FileOutputStream("3_150x150.jpg");
			stream.write(bytes);
		} catch (IOException e) {
			e.printStackTrace();
		}

文件删除

	fastFileStorageClient.deleteFile("group1","M00/00/00/wKgDDGDub22AWGB_AApS0I7eS2
U026.jpg");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
FastDFS是一个开源的轻量级分布式文件系统,它提供了高性能的文件存储和访问服务。Spring Boot是一个用于构建独立的、生产级别的Spring应用程序的框架。将FastDFS集成到Spring Boot中可以实现在Spring应用程序中使用FastDFS提供的文件存储和访问服务。 要实现FastDFS集成Spring Boot,你可以按照以下步骤进行操作: 1. 引入FastDFS的依赖:在Spring Boot项目的pom.xml文件中,添加FastDFS的依赖。你可以在Maven中央仓库中找到FastDFS的相关依赖。 2. 配置FastDFS的连接信息:在Spring Boot配置文件(application.properties或application.yml)中,配置FastDFS的连接信息,如Tracker服务器的地址、端口号等。 3. 编写FastDFS的客户端:在Spring Boot应用程序中编写FastDFS客户端的代码,用于连接FastDFS服务器,并实现文件的上传、下载、删除等操作。 4. 集成Swagger:如果你想方便地测试和使用FastDFS的功能,你可以集成Swagger,它提供了一个用户友好的API文档和测试界面。 通过以上步骤,你就可以实现FastDFS集成到Spring Boot中,从而在Spring Boot应用程序中使用FastDFS的文件存储和访问服务。<span class="em">1</span> #### 引用[.reference_title] - *1* [FastDFS源码封装(SpringBoot集成FastDFS)](https://download.csdn.net/download/fjxcsdn/12051041)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值