Springboot 2.1 Practice Course (22)-Integrate FastDFS (2), fastdfs_client based on tobato

The author of the fastdfs_client open source project is the tobato
project address: https://github.com/tobato/FastDFS_Client
It is a java client third-party component for fastDFS, based on the java client released by the original author YuQing and yuqih. For developers, it
is more convenient and elegant to call FastDFS services.

How to use fastdfs_client?

This project is based on the SpringBoot2.x framework, the specific operations are as follows:

1. Add dependencies to the project Pom

Maven depends on

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

2. Introduce Fdfs configuration into the project

After configuring dependencies in Maven, SpringBoot projects will automatically import FastDFS dependencies

FastDFS-Client introduced before version 1.26.4

The way to introduce the FastDFS-Client client into the localization project is very simple, /src/[com.xxx.主目录]/confconfigure it in the SpringBoot project

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

Only one line of annotation @Import(FdfsClientConfig.class) is needed to have a FastDFS Java client with connection pool.

3. Configure Fdfs related parameters in application.yml

# ===================================================================
# 分布式文件系统FDFS配置
# ===================================================================
fdfs:
  so-timeout: 1501
  connect-timeout: 601 
  thumb-image:             #缩略图生成参数
    width: 150
    height: 150
  tracker-list:            #TrackerList参数,支持多个
    - 192.168.1.105:22122
    - 192.168.1.106:22122 

4. Perform corresponding operations on files through the FastDFS-Client interface service

First, write a tool class FastdfsClientUtil to encapsulate the corresponding operations and implement them respectively:

  • upload files

  • download file

  • Delete Files

  • Upload pictures and generate thumbnails

package org.learn.utils;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.fdfs.ThumbImageConfig;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * FastDFS工具类
 */
@Component
public class FastdfsClientUtil {
    
    
    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private ThumbImageConfig thumbImageConfig;


    /**
     * 上传文件
     *
     * @param file 文件对象
     * @return 文件访问地址
     * @throws IOException
     */
    public String uploadFile(MultipartFile file) throws IOException {
    
    
        StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(),
                file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()), null);
        return storePath.getFullPath();
    }


    /**
     * 下载文件
     *
     * @param fileUrl 文件URL
     * @return 文件字节
     * @throws IOException
     */
    public byte[] downloadFile(String fileUrl) throws IOException {
    
    
        String group = fileUrl.substring(0, fileUrl.indexOf("/"));
        String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
        DownloadByteArray downloadByteArray = new DownloadByteArray();
        byte[] bytes = fastFileStorageClient.downloadFile(group, path,
                downloadByteArray);
        return bytes;
    }

    /**
     * 删除文件
     *
     * @Param fileUrl 文件访问地址
     */
    public void deleteFile(String fileUrl) {
    
    
        if (StringUtils.isEmpty(fileUrl)) {
    
    
            return;
        }
        try {
    
    
            StorePath storePath = StorePath.parseFromUrl(fileUrl);
            fastFileStorageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (FdfsUnsupportStorePathException e) {
    
    
            e.printStackTrace();
        }
    }


    /**
     * 上传图片,并生成缩略图
     */
    public Map<String, String> uploadImageAndCrtThumbImage(MultipartFile file) throws IOException {
    
    
        Map<String, String> map = new HashMap<>();
        StorePath storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(file.getInputStream(),
                file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()), null);

        // 这里需要一个获取从文件名的能力,所以从文件名配置以后就最好不要改了
        String slavePath = thumbImageConfig.getThumbImagePath(storePath.getPath());
        map.put("path", storePath.getFullPath());  //原路径图片地址
        map.put("slavePath", slavePath);            //缩略图图片地址
        return map;
    }


}

5. Write the Controller class

package org.learn.controller;

import org.learn.utils.FastdfsClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

/**
 * FastDFS上传文件控制器
 */
@Controller
public class FdfsClientController {
    
    

    private static Logger logger = LoggerFactory.getLogger(FdfsClientController.class);
    @Autowired
    private FastdfsClientUtil fastdfsClientUtil;


    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @RequestMapping("/uploadFile")
    public String uploadFile(@RequestParam("file") MultipartFile file, Model view) {
    
    
        try {
    
    
            String path = fastdfsClientUtil.uploadFile(file);
            System.out.println("path:" + path);
            view.addAttribute("uri", path);

        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

        return "index";
    }

    /**
     * 下载文件
     *
     * @param filePath
     * @param response
     * @return
     */
    @RequestMapping("/downloadFile")
    public void downloadFile(@RequestParam("filePath") String filePath, HttpServletResponse response) {
    
    
        int index = filePath.lastIndexOf("/");
        String fileName = filePath.substring(index + 1);
        try {
    
    
            byte[] bytes = fastdfsClientUtil.downloadFile(filePath);
            InputStream inputStream = new ByteArrayInputStream(bytes);
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            byte[] buff = new byte[1024];
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buff);
            while (i != -1) {
    
    
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
            os.close();
            bis.close();
            logger.info("Download  successfully!");


        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

    }

    /**
     * 删除文件
     *
     * @param filePath
     * @return
     */
    @RequestMapping("/deleteFile")
    @ResponseBody
    public String deleteFile(@RequestParam("filePath") String filePath) {
    
    
        fastdfsClientUtil.deleteFile(filePath);

        return  "删除文件成功";
    }

    /**
     * 上传图片,并且生成缩略图
     */

    @RequestMapping("/uploadImageAndCrtThumbImage")
    public String uploadImageAndCrtThumbImage(@RequestParam("file") MultipartFile file, Model view) {
    
    

        try {
    
    
            //上传图片,并且生成缩略图的方法
            Map<String, String> map = fastdfsClientUtil.uploadImageAndCrtThumbImage(file);

            view.addAttribute("uri", map.get("path"));//原图片地址
            view.addAttribute("slavePath", map.get("slavePath"));  //缩略图地址

        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

        return "index";
    }

}

6. Write a page for uploading files

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
hello,你已经进入到首页
<span th:text="${uri}"></span>
<form action="/uploadFile" enctype="multipart/form-data" method="post">
    文件上传<input type="file" name="file" id="file"/>

    <input type="submit" value="提交">

</form>
</body>
</html>

7. Demo upload and download operations

Demonstrate uploading, downloading, deleting, generating thumbnails and obtaining a picture

  • upload files

Visit the page and perform the upload operation
Insert picture description here
Insert picture description here

After the upload is successful, the page returns the address of the file. Next, we will directly access the image in the browser. Remember to bring the IP: port of the file server. If the image can be displayed normally, the upload is successful.
Insert picture description here

  • download file

    Initiate a file download request directly in the browser, the address is as follows

    http://localhost:8080/downloadFile?filePath=group1/M00/00/00/wKgBa18vqWCAakxaAAW8VIh03qE499.png
    Insert picture description here

  • Delete Files

Perform the file deletion operation in the browser, the address is as follows:

http://localhost:8080/deleteFile?filePath=group1/M00/00/00/wKgBa18vqWCAakxaAAW8VIh03qE499.png
Insert picture description here

  • Generate thumbnails and get

The first choice is to change the upload request of the homepage to upload an image and generate a thumbnail interface, /uploadImageAndCrtThumbImage

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
hello,你已经进入到首页
<span th:text="${uri}"></span>
<form action="/uploadImageAndCrtThumbImage" enctype="multipart/form-data" method="post">
    文件上传<input type="file" name="file" id="file"/>

    <input type="submit" value="提交">

</form>
</body>
</html>

After the upload operation is performed, the file server will generate the corresponding thumbnail file, and we only need to bring the thumbnail suffix after the address we requested, such as:

源图 http://192.168.1.107:8085/M00/00/17/rBEAAl33pQaAWNQNAAHYvQQn-YE374.jpg
缩略图 http://192.168.1.107:8085/M00/00/17/rBEAAl33pQaAWNQNAAHYvQQn-YE374_150x150.jpg

Insert picture description here

Guess you like

Origin blog.csdn.net/java_cxrs/article/details/107895232