FastDFS整合SpringBoot

Posted 天宇轩-王

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了FastDFS整合SpringBoot相关的知识,希望对你有一定的参考价值。

  • pom.xml
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>



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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
  • 配置类

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

}

  • 包装类
@Component
public class FastDFSClientWrapper {
 
    private final Logger logger = LoggerFactory.getLogger(FastDFSClientWrapper.class);
 
    @Autowired
    private FastFileStorageClient fastFileStorageClient;
 
    /**
     * 文件上传
     * 最后返回fastDFS中的文件名称;group1/M00/01/04/CgMKrVvS0geAQ0pzAACAAJxmBeM793.doc
     *
     * @param bytes     文件字节
     * @param fileSize  文件大小
     * @param extension 文件扩展名
     * @return fastDfs路径
     */
    public String uploadFile(byte[] bytes, long fileSize, String extension) {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        StorePath storePath = fastFileStorageClient.uploadFile(byteArrayInputStream, fileSize, extension, null);
        logger.info(storePath.getGroup() + "==" + storePath.getPath() + "======" + storePath.getFullPath());
        return storePath.getFullPath();
    }
 
    /**
     * 下载文件
     *  返回文件字节流大小
     * @param fileUrl 文件URL
     * @return 文件字节
     * @throws IOException
     */
    public byte[] downloadFile(String group,String path) throws IOException {
        DownloadByteArray downloadByteArray = new DownloadByteArray();
        byte[] bytes = fastFileStorageClient.downloadFile(group, path, downloadByteArray);
        return bytes;
    }
 
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <meta charset="UTF-8" />
    <title>Insert title here</title>
</head>
<body>
<h1 th:inlines="text">文件上传</h1>
<form action="upload" method="post" enctype="multipart/form-data">
    <p>选择文件: <input type="file" name="file"/></p>
    <p><input type="submit" value="提交"/></p>
</form>
</body>
</html>
  • application.yml
#fastdfs 配置
fdfs:
  so-timeout: 1500
  connect-timeout: 600
  thumb-image:
    width: 150
    height: 150
  tracker-list:
    - 192.168.180.104:22122
spring:
  thymeleaf:
    prefix: classpath:/templates/
  • web层
@RestController
public class FdfsController {
    
    @Autowired
    private FastDFSClientWrapper fastDFSClientWrapper;
    
    private final Logger logger = LoggerFactory.getLogger(FdfsController.class);
    
    @RequestMapping("file")
    public String file(){
        return "/fileUploade";
    }
    
    @PostMapping("/upload")
    public void upload(MultipartFile file) throws Exception {
        byte[] bytes = new byte[0];
        try {
            bytes = file.getBytes();
        } catch (IOException e) {
            logger.error("获取文件错误");
            e.printStackTrace();
        }
        //获取源文件名称
        String originalFileName = file.getOriginalFilename();
        //获取文件后缀--.doc
        String extension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
        String fileName = file.getName();
        //获取文件大小
        long fileSize = file.getSize();
        System.out.println(originalFileName + "==" + fileName + "==" + fileSize + "==" + extension + "==" + bytes.length);
         String string = fastDFSClientWrapper.uploadFile(bytes, fileSize, extension);
         //group1/M00/00/00/wKi0aF3I4dOAIhAXAAAG7e1-evI891.txt
         System.out.println(string);
    }
    
    @GetMapping("/downloadFile")
    public void downloadFile(String group,String path,String fileName,HttpServletResponse response) throws Exception {
        byte[] bytes = fastDFSClientWrapper.downloadFile(group, path);
        //设置相应类型application/octet-stream (注:applicatoin/octet-stream 为通用,一些其它的类型苹果浏览器下载内容可能为空)
        response.reset();
        response.setContentType("applicatoin/octet-stream");
        //设置头信息                 Content-Disposition为属性名  附件形式打开下载文件   指定名称  为 设定的fileName
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        // 写入到流
        ServletOutputStream out = response.getOutputStream();
        out.write(bytes);
        out.close();

    }
       
    


}

技术图片

 

以上是关于FastDFS整合SpringBoot的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot整合FastDFS实现文件的上传下载和删除

FastDFS快速实现和SpringBoot的整合开发

SpringBoot2.0集成FastDFS

SpringBoot项目整合FastDFS+Nginx实现图片上传

SpringBoot集成FastDFS+Nginx整合基于Token的防盗链

SpringBoot实现上传文件到fastDFS文件服务器