springboot 2.1 实践教程(二十一)-整合FastDFS

整合步骤:

  • 创建SpringBoot项目
    springboot 2.1 实践教程(二十一)-整合FastDFS_第1张图片

  • 引入fastdfs-client-java包

<dependency>
            <groupId>org.csource</groupId>
            <artifactId>fastdfs-client-java</artifactId>
            <version>1.28</version>
 </dependency>
  • 在 resources 目录下新建 fdfs_client.conf 文件
tracker_server = 192.168.1.107:22122
  • 编写FastDFS工具类FastdfsClientUtil.java用于封装上传、下载、删除文件等方法。
package org.learn.utils;

import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * FastDFS上传工具类
 */
@Component
public class FastdfsClientUtil {
    private static final Logger logger = LoggerFactory
            .getLogger(FastdfsClientUtil.class);

    private static final String CONFIG_FILENAME = "fdfs_client.conf";

    // 加载文件
    static {
        try {
            ClientGlobal.init(CONFIG_FILENAME);
            logger.info("初始化 Fastdfs Client 配置信息:{}", ClientGlobal.configInfo());

        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
    }

    /**
     * 上传文件
     * @param fileContent
     * @param extName
     * @return
     * @throws Exception
     */
    public String[] uploadFile(byte[] fileContent, String extName) {

        try {
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getTrackerServer();
            StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
            StorageClient storageClient = new StorageClient(trackerServer, storageServer);
            return storageClient.upload_file(fileContent, extName, null);

        } catch (Exception e) {
            logger.error(e.toString(), e);
            return null;
        }

    }

    /**
     * 下载文件
     * @param groupName
     * @param fileId
     * @return
     */
    public byte[] downloadFile(String groupName, String fileId) {
        try {
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getTrackerServer();
            StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
            StorageClient storageClient = new StorageClient(trackerServer, storageServer);
            byte[] fileByte = storageClient.download_file(groupName, fileId);
            return fileByte;
        } catch (Exception e) {
            logger.error(e.toString(), e);
            return null;
        }
    }


    /**
     * 删除文件
     * @param groupName
     * @param remoteFilename
     * @return
     */
    public int deleteFile(String groupName, String remoteFilename) {

        try {
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getTrackerServer();
            StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
            StorageClient storageClient = new StorageClient(trackerServer, storageServer);
            int i = storageClient.delete_file(groupName, remoteFilename);
            logger.info("delete file successfully!!!" + i);
            return 1;
        } catch (Exception e) {
            logger.error(e.toString(), e);
            return 0;
        }

    }
}

  • 编写Controller类FdfsClientController.java用于处理FastDFS上传下载功能。
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;

/**
 * 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 origFileName = file.getOriginalFilename();
            logger.info("原始文件名:{}", origFileName);

            // 获取扩展名
            String extName = origFileName.substring(origFileName.lastIndexOf(".") + 1);
            logger.info("原始文件扩展名:{}", extName);

            // 获取文件存储路径
            String[] uriArray = new String[0];

            uriArray = fastdfsClientUtil.uploadFile(file.getBytes(), extName);

            String groupName = uriArray[0];
            String fileId = uriArray[1];

            String uri = groupName + "/" + fileId;
            logger.info("返回的文件存储路径:{}", uri);
            view.addAttribute("uri", uri);


            return "index";
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 下载文件
     *
     * @param filePath
     * @param response
     * @return
     */
    @RequestMapping("/downloadFile")
    public void downloadFile(@RequestParam("filePath") String filePath, HttpServletResponse response) {

        try {


            String group = filePath.substring(0, filePath.indexOf("/"));
            String path = filePath.substring(filePath.indexOf("/") + 1);
            int index = filePath.lastIndexOf("/");
            String fileName = filePath.substring(index + 1);
            //group1/M00/00/00/wKgBa18meFmAHaVYAAW8VIh03qE244.png
            /**
             * 参数格式:
             * groupName: group1
             * fileId: M00/00/00/wKgBa18meFmAHaVYAAW8VIh03qE244.png
             */
            byte[] fileByte = fastdfsClientUtil.downloadFile(group, path);
            InputStream inputStream = new ByteArrayInputStream(fileByte);
            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 (Exception e) {
            logger.error(e.toString(), e);
        }

    }


    /**
     * 删除文件
     *
     * @param filePath
     * @return
     */
    @RequestMapping("/deleteFile")
    @ResponseBody
    public String deleteFile(@RequestParam("filePath") String filePath) {
        try {
            /**
             * 参数格式:
             * groupName: group1
             * fileId:M00/00/00/wKgBa18meFmAHaVYAAW8VIh03qE244.png
             */
            String group = filePath.substring(0, filePath.indexOf("/"));
            String path = filePath.substring(filePath.indexOf("/") + 1);

            int i = fastdfsClientUtil.deleteFile(group, path);
            return (i > 0) ? "删除文件成功" : "删除文件失败";
        } catch (Exception e) {
            logger.error(e.toString(), e);
            return null;
        }

    }

}

  • 编写上传页面index.html,实现上传一个文件,并能下载获取到该文件。
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
hello,你已经进入到首页
<form action="/uploadFile" enctype="multipart/form-data" method="post">
    文件上传<input type="file" name="file" id="file"/>

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

</form>
</body>
</html>
  • 测试FastDFS是否整合成功

    测试上传图片

    选择上传的文件,提交
    springboot 2.1 实践教程(二十一)-整合FastDFS_第2张图片

提交后,图片上传成功,返回上传的路径
springboot 2.1 实践教程(二十一)-整合FastDFS_第3张图片

下载图片,执行下载方法,将图片的路径地址作为传输传递到下载方法中

http://localhost:8080/downloadFile?filePath=group1/M00/00/00/wKgBa18mfs2ABii9AAW8VIh03qE824.png

删除图片,执行删除方法,将图片的路径地址作为参数传递到删除方法中
springboot 2.1 实践教程(二十一)-整合FastDFS_第4张图片

具体测试代码请在我的码云项目中下载

地址:源码下载地址

你可能感兴趣的:(FastDFS,Spring,Boot2.1实践教程,spring,spring,boot,fastdfs)