java整合fastdfs实现文件上传下载

在虚拟机搭建fastdfs服务和nginx的请参考我的这个博文centos7搭建fastdfs通过nginx访问保姆级教程

1.添加fastDFS_Client依赖

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

2.在application.yml中添加如下fdfs配置

fdfs:
  so-timeout: 1501
  connect-timeout: 601
  thumb-image:             #缩略图生成参数
    width: 150
    height: 150
  tracker-list:            #TrackerList参数,支持多个
    - 192.168.206.130:22122
  web-server-url: http://192.168.206.130:8080/  # 设置前缀路径

3.文件操作示例

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 org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("fastdfs")
public class FileClientController {

    @Resource
    FastFileStorageClient fastFileStorageClient;

    @Value("${fdfs.web-server-url}")
    private String baseUrl;

    /**
     * 文件上传
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    public String upload(@RequestBody MultipartFile file, HttpServletRequest request) throws Exception {
        StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(),
                file.getSize(),
                StringUtils.substringAfterLast(file.getOriginalFilename(), "."),
                null);
        System.out.println("***"+storePath.getFullPath());
        System.out.println( baseUrl + storePath.getFullPath());
        return baseUrl + storePath.getFullPath();
    }

    /**
     * @param groupName
     * @param fileKey
     * @param response
     */
    @PostMapping("/download")
    public void download(String groupName, String fileKey, HttpServletResponse response) {
        byte[] download = fastFileStorageClient.downloadFile(groupName, fileKey, new DownloadByteArray());
        ByteArrayInputStream bais = new ByteArrayInputStream(download);
        try {
            String fileName = fileKey.substring(fileKey.lastIndexOf("/")+1);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            ServletOutputStream out = response.getOutputStream();
            byte[] content = new byte[1024];
            int length = -1;
            while ((length = bais.read(content)) != -1) {
                out.write(content, 0, length);
                out.flush();
            }
            out.close();
            bais.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 删除文件
     * @param filePath 文件的完整路径
     */
   @PostMapping("/delete")
    public Result delFile(String filePath)  {
        try {
            fastFileStorageClient.deleteFile(filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result().err();
        }
        return new Result().ok();
    }
}


4.文件上传配置

import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;

import javax.servlet.MultipartConfigElement;

/**
 * 文件上传配置
 */
@Configuration
public class FileConfig {

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //单个文件最大  50MB
        factory.setMaxFileSize(DataSize.ofBytes(50 * 1024 *1024));
        /// 设置总上传数据总大小 200MB
        factory.setMaxRequestSize(DataSize.ofBytes(200 * 1024 *1024));
        return factory.createMultipartConfig();
    }
}


5.postman测试效果如图

在这里插入图片描述
一定要记得关闭fastdfs端服务器的防火墙
systemctl stop firewalld

  • 38
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

迪霸戈

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

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

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

打赏作者

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

抵扣说明:

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

余额充值