java 整合FastDFS文件服务

738 阅读6分钟

java整合fdfs文件服务器

1. 服务器fastdfs搭建

参考地址,亲测有效,Centos7.6版本

2. java代码部分

2.1 引入相关依赖包

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

2.2 FDFS 配置类

@Configuration
@Import(FdfsClientConfig.class) // 导入FastDFS-Client组件
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) // 解决jmx重复注册bean的问题
public class FdfsConfiguration {
}

2.3 配置文件

# 分布式文件系统fastdfs配置
fdfs:
 # socket连接超时时长
 soTimeout: 1500
 # 连接tracker服务器超时时长
 connectTimeout: 600
 # nginx 访问的地址和端口
 reqHost: 114.55.164.189
 reqPort: 80
 pool:
   # 从池中借出的对象的最大数目
   max-total: 153
   # 获取连接时的最大等待毫秒数100
   max-wait-millis: 102
 # 缩略图生成参数,可选
 thumbImage:
   width: 150
   height: 150
 # 跟踪服务器tracker_server请求地址,支持多个,这里只有一个,如果有多个在下方加- x.x.x.x:port
 trackerList:
   - 114.55.164.189:22122
 #
 # 存储服务器storage_server访问地址
 web-server-url: http://114.55.164.189:80/

2.4 读取配置文件的实体类

@Data
@ConfigurationProperties(prefix = "fdfs",ignoreInvalidFields = true)
@Slf4j
public class FastdfsProperties implements InitializingBean {


    private String reqHost;

    private String reqPort;

    private String webServerUrl;

    private String soTimeout;

    @Override
    public void afterPropertiesSet() throws Exception {
        log.debug("fdfs.reqHost is {},fdfs.reqPort is {},fdfs.webServerUrl is {}",getReqHost(),getReqPort(),getWebServerUrl());
        if (StringUtils.isBlank(getReqHost())) {
            throw new IllegalStateException("Property \"fdfs.reqHost\" cannot  be blank");
        }
        if (StringUtils.isBlank(getReqPort())) {
            throw new IllegalStateException("Property \"fdfs.reqPort\" cannot  be blank");
        }
        if (StringUtils.isBlank(getWebServerUrl())) {
            throw new IllegalStateException("Property \"fdfs.webServerUrl\" cannot  be blank");
        }
        if (StringUtils.isBlank(getSoTimeout())) {
            throw new IllegalStateException("Property \"fdfs.soTimeout\" cannot  be blank");
        }

    }
}

注意启动类需要添加自动加载配置类注解 @EnableConfigurationProperties({ApplicationProperties.class,FastdfsProperties.class})

2.5 工具类

@Component
public class FastDFSClient {

    private  Logger log = LoggerFactory.getLogger(FastDFSClient.class);

    @Autowired
    FastdfsProperties fastdfsProperties;


    @Autowired
    private  FastFileStorageClient storageClient;

    @Autowired
    private  ThumbImageConfig imageConfig;   //创建缩略图的

    @Autowired
    private  TrackerClient trackerClient;


    /**
     * 简单文件上传
     * @param file
     * @return
     */
    public  String upload (MultipartFile file){
        String fileName  = file.getOriginalFilename();
        try {
            InputStream inputStream= file.getInputStream();

            long size = file.getSize();

            StorePath path = storageClient.uploadFile(inputStream,size,fileName.substring(fileName.lastIndexOf(".")+ 1), null);

            return getResAccessUrl(path);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.toString());
            return null;
        }
    }

    /**
     * 删除指定文件
     * @param url
     */
    public  void delFile (String url){
        storageClient.deleteFile(url);
    }


    /**
     * 文件下载
     * @param fileUrl
     * @return
     * @throws IOException
     */
    public byte[] downloadFile(String fileUrl) throws IOException {
        fileUrl = fileUrl.replaceAll(fastdfsProperties.getWebServerUrl(),"");
        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;
    }
    /**
     * 获取文件路径
     * @param path
     * @return
     */
    private  String getResAccessUrl(StorePath path) {
        String fileUrl = "http://" +  fastdfsProperties.getReqHost() + ":" +  fastdfsProperties.getReqPort() +  "/" + path.getFullPath();
        return fileUrl;
    }
}

2.6 测试

@RestController
@RequestMapping("/file")
@Api(tags = "文件管理")
public class UploadController {

    @Autowired
    private FastDFSClient fastDFSClient;


    @ApiOperation(value = "文件上传")
    @RequestMapping(value = "/upload" ,method = RequestMethod.POST)
    public Result upload(
            @RequestParam("file")  MultipartFile file
    ){

        if(file == null || file.isEmpty()){
            return new Result(RetCode.PARAM_ERROR.getCode(),RetCode.PARAM_ERROR.getMsg(),null);
        }
        String path = fastDFSClient.upload(file);
        return new Result(RetCode.SUCCESS.getCode(),RetCode.SUCCESS.getMsg(),path);

    }

    @ApiOperation(value = "删除文件")
    @RequestMapping(value = "/del" ,method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "文件全路径" ,name = "url" ,required = true,dataType = "String",paramType = "query")
    })
    public Result delFile(String url){
        if(url == null || url.equals("")){
            return new Result(RetCode.PARAM_ERROR.getCode(),RetCode.PARAM_ERROR.getMsg(),null);
        }
        try {
            fastDFSClient.delFile(url);
            return new Result(RetCode.SUCCESS.getCode(),RetCode.SUCCESS.getMsg(),null);
        } catch (Exception e){
            return new Result(RetCode.PARAM_VALUE_ERROR.getCode(),RetCode.PARAM_VALUE_ERROR.getMsg(),null);
        }


    }

    @ApiOperation(value = "文件下载")
    @GetMapping("/downLoad")
    public ResponseEntity<byte []downLoadFile(
            @ApiParam(value = "文件路径",required = true) @RequestParam(value = "url" ,required = true) String url
    ) {
        try {
            byte[] bytes = fastDFSClient.downloadFile(url);

            String fileName =url.substring(url.lastIndexOf("/" +1));
            fileName = new String(fileName.getBytes("utf-8"),"ISO_8859_1");

            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            httpHeaders.setContentDispositionFormData("attachment", fileName);

            return new ResponseEntity<byte[]>(bytes,httpHeaders,HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}

2.6 文件下载(返回的是字节码数组,可以直接在前端下载文件)

前端文件下载参考