(二十四)ATP应用测试平台——springboot集成fastdfs上传与下载功能

前言

本节内容我们主要介绍一下如何在springboot项目中集成fastdfs组件,实现文件的上传与下载。关于fastdfs服务中间键的安装过程,本节内容不做介绍。fastdfs是一个轻量级的分布式文件系统,也是我们文件存储中常常使用的组件之一,主要包括文件存储、文件同步、文件访问,实现了文件存储和负载均衡的问题。

正文

①引入fastdfs客户端的maven依赖


    com.github.tobato
    fastdfs-client
    1.27.2

(二十四)ATP应用测试平台——springboot集成fastdfs上传与下载功能_第1张图片

 ②在application.yml配置fastdfs的属性参数值

fdfs:
  so-timeout: 1501 # 超时时间
  connect-timeout: 601 # 连接超时时间
  tracker-list: # tracker地址:你的虚拟机服务器地址+端口(默认是22122)
    - 125.27.107.218:22122

(二十四)ATP应用测试平台——springboot集成fastdfs上传与下载功能_第2张图片

 ③引入fastdfs客户端组件,交由spring管理

package com.ht.atp.plat.config;

import com.github.tobato.fastdfs.FdfsClientConfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy;


@Configuration
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FastDfsConfig {

}

(二十四)ATP应用测试平台——springboot集成fastdfs上传与下载功能_第3张图片

 ④创建springboot文件上传与下载的控制层接口FdfsRecordController.class

package com.ht.atp.plat.controller;

import com.ht.atp.plat.common.Result;
import com.ht.atp.plat.service.FdfsRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Api(tags = {"文件管理"})
@RestController
@RequestMapping("/v1/fdfs/record")
public class FdfsRecordController {
    @Autowired
    private FdfsRecordService fdfsRecordService;

    @ApiOperation(value = "文件上传")
    @PostMapping(value = "uploadFile")
    public Result uploadFile(
            @ApiParam(name = "file", value = "上传的文件")
            @RequestParam(value = "file") MultipartFile file) {
        String url = fdfsRecordService.uploadFile(file);
        return Result.success(url);
    }


    @ApiOperation(value = "文件下载")
    @GetMapping(value = "downloadFile")
    public Result downloadFile(
            @ApiParam(name = "url", value = "下载地址")
            @RequestParam(value = "url") String url) {
        String data = fdfsRecordService.downloadFile(url);
        return Result.success(data);
    }

}

(二十四)ATP应用测试平台——springboot集成fastdfs上传与下载功能_第4张图片

 ⑤创建springboot文件上传与下载的业务接口层FdfsRecordService.class

package com.ht.atp.plat.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.ht.atp.plat.entity.FdfsRecord;
import org.springframework.web.multipart.MultipartFile;


public interface FdfsRecordService extends IService {
    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    String uploadFile(MultipartFile file);

    /**
     * 文件下载
     * @param url
     * @return
     */
    String downloadFile(String url);
}

  ⑥创建springboot文件上传与下载的业务接口实现层FdfsRecordServiceImpl.class

package com.ht.atp.plat.service.impl;

import cn.hutool.core.codec.Base64;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.ht.atp.plat.entity.FdfsRecord;
import com.ht.atp.plat.exception.BusinessException;
import com.ht.atp.plat.mapper.FdfsRecordMapper;
import com.ht.atp.plat.service.FdfsRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.time.LocalDateTime;


@Service
public class FdfsRecordServiceImpl extends ServiceImpl implements FdfsRecordService {
    @Autowired
    private FastFileStorageClient storageClient;

    @Override
    public String uploadFile(MultipartFile file) {
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null) {
                throw new BusinessException("文件内容不合法,无法上传!");
            }
            String fileName = file.getOriginalFilename();
            String suffix = "";
            if (StringUtils.isNotEmpty(fileName)) {
                String[] splitFileName = fileName.split("\\.");
                if (splitFileName != null && splitFileName.length > 1) {
                    suffix = splitFileName[splitFileName.length - 1];
                }
            }
            FdfsRecord fdfsRecord = new FdfsRecord();
            fdfsRecord.setModifyTime(LocalDateTime.now());
            fdfsRecord.setCreateTime(LocalDateTime.now());
            fdfsRecord.setSuffixName(suffix);
            fdfsRecord.setName(fileName);
            StorePath storePath = this.storageClient.uploadFile(file.getInputStream(), file.getSize(), suffix, null);
            fdfsRecord.setUrl(storePath.getFullPath());
            baseMapper.insert(fdfsRecord);
            return storePath.getFullPath();
        } catch (Exception e) {
            throw new BusinessException("文件上传服务异常,请稍后重试!");
        }
    }

    @Override
    public String downloadFile(String url) {
        String group = url.substring(0, url.indexOf("/"));
        String path = url.substring(url.indexOf("/") + 1);
        DownloadByteArray byteArray = new DownloadByteArray();
        byte[] data = this.storageClient.downloadFile(group, path, byteArray);
        String encodeData = Base64.encode(data);
        return encodeData;
    }
}

⑦创建springboot文件资源信息存储的持久化层FdfsRecordMapper.class,实现文件资源信息的持久化存储

package com.ht.atp.plat.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ht.atp.plat.entity.FdfsRecord;


public interface FdfsRecordMapper extends BaseMapper {

}

⑧创建springboot文件资源信息存储的持久化层FdfsRecordMapper.xml,实现文件资源信息的持久化存储






 ⑨创建springboot文件资源信息存储的实体类FdfsRecord.class

package com.ht.atp.plat.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.time.LocalDateTime;


@Getter
@Setter
@TableName("fdfs_record")
@ApiModel(value = "FdfsRecord对象", description = "")
public class FdfsRecord implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty("主键ID")
    @TableId(value = "id", type = IdType.ASSIGN_ID)
    private String id;

    @ApiModelProperty("业务ID")
    @TableField("business_id")
    private String businessId;

    @ApiModelProperty("服务名称")
    @TableField("service_name")
    private String serviceName;

    @ApiModelProperty("文件名称")
    @TableField("name")
    private String name;

    @ApiModelProperty("文件地址")
    @TableField("url")
    private String url;

    @ApiModelProperty("后缀名称")
    @TableField("suffix_name")
    private String suffixName;

    @ApiModelProperty("创建时间")
    @TableField("create_time")
    private LocalDateTime createTime;

    @ApiModelProperty("创建人")
    @TableField("create_user")
    private String createUser;

    @ApiModelProperty("修改时间")
    @TableField("modify_time")
    private LocalDateTime modifyTime;

    @ApiModelProperty("修改人")
    @TableField("modify_user")
    private String modifyUser;


}

⑩ 使用swagger测试文件上传功能

(二十四)ATP应用测试平台——springboot集成fastdfs上传与下载功能_第5张图片

 ⑪使用swagger测试文件下载功能

(二十四)ATP应用测试平台——springboot集成fastdfs上传与下载功能_第6张图片

结语

通过至此,关于springboot集成fastdfs上传与下载功能到这里就结束了,下期见。。。

你可能感兴趣的:(ATP应用测试平台,dfs,中间件)