前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java整合FastDFS文件服务器

java整合FastDFS文件服务器

作者头像
java攻城狮
发布2020-10-10 16:34:18
3.9K0
发布2020-10-10 16:34:18
举报
文章被收录于专栏:个人积累个人积累

java整合fdfs文件服务器

1. 服务器fastdfs搭建

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

2. java代码部分

2.1 引入相关依赖包
代码语言:javascript
复制
    <dependency>
      <groupId>com.github.tobato</groupId>
      <artifactId>fastdfs-client</artifactId>
      <version>1.26.5</version>
    </dependency>
2.2 FDFS 配置类
代码语言:javascript
复制
@Configuration
@Import(FdfsClientConfig.class) // 导入FastDFS-Client组件
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) // 解决jmx重复注册bean的问题
public class FdfsConfiguration {
}
2.3 配置文件
代码语言:javascript
复制
# 分布式文件系统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 读取配置文件的实体类
代码语言:javascript
复制
@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 工具类
代码语言:javascript
复制
@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 测试
代码语言:javascript
复制
@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;
        }
    }

}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-09-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • java整合fdfs文件服务器
    • 1. 服务器fastdfs搭建
      • 2. java代码部分
        • 2.1 引入相关依赖包
        • 2.2 FDFS 配置类
        • 2.3 配置文件
        • 2.4 读取配置文件的实体类
        • 2.5 工具类
        • 2.6 测试
    相关产品与服务
    云 HDFS
    云 HDFS(Cloud HDFS,CHDFS)为您提供标准 HDFS 访问协议,您无需更改现有代码,即可使用高可用、高可靠、多维度安全、分层命名空间的分布式文件系统。 只需几分钟,您就可以在云端创建和挂载 CHDFS,来实现您大数据存储需求。随着业务需求的变化,您可以实时扩展或缩减存储资源,CHDFS 存储空间无上限,满足您海量大数据存储与分析业务需求。此外,通过 CHDFS,您可以实现计算与存储分离,极大发挥计算资源灵活性,同时实现存储数据永久保存,降低您大数据分析资源成本。
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档