springboot精华文章(文件上传)——通过FastDFS+nginx实现文件上传下载删除等操作

(B站云e办)SpringBoot开发项目实战记录(结)

  • 引言: 本文使用Centos7部署fastDFS+nginx
  • 一、 fastDFS所需要的pom
    • 1.2 引入fastDFS的pom
    • 1.2引入fastDFS的pom失败解决方案
  • 二、fastDFS的配置文件
  • 三、fastDFS的工具类编写
    • 3.1 加载fastDFS配置
    • 3.2 fastDFS的文件上传
    • 3.3 fastDFS的获取文件信息
    • 3.4 fastDFS的文件下载
    • 3.5 fastDFS的文件删除
    • 3.6 fastDFS的获取storageClient、获取trackerServer
    • 3.7 fastDFS的获取服务的运行服务器地址
    • 3.8 整体文件,点我进行复制
  • 四、 上传一个图片具体应用
    • 4.1 controller层
    • 4.2 service层

引言: 本文使用Centos7部署fastDFS+nginx

热烈推荐该网址进行优先配置:点我跳转

一、 fastDFS所需要的pom

1.2 引入fastDFS的pom

		<dependency>
            <groupId>org.csourcegroupId>
            <artifactId>fastdfs-client-javaartifactId>
            <version>1.29-SNAPSHOTversion>
        dependency>

1.2引入fastDFS的pom失败解决方案

由于这pom好像maven不再维护,可以下载到本地再加载到本地maven仓库,然后引入就不会报错了,具体解决我是参考这个文章:点我跳转

二、fastDFS的配置文件

# 连接超时
connect_timeout = 2
# 网络超时
network_timeout = 30
# 编码格式
charset = UTF-8
# tracker端口号
http.tracker_http_port = 8080
# 防盗链功能
http.anti_steal_token = no
# 密钥
http.secret_key = FastDFS123457890
# tracker_ip: 端口号
tracker_server = 自己的fastDFS服务地址:22122
# 连接池配置
connection_pool.enable = true
connection_pool.max_count_per_entry = 500
connection_pool.max_idle_time = 3600
connection_pool.max_wait_time_in_ms = 1000

三、fastDFS的工具类编写

拆开各个功能,最后一个为整体文件,直接cv

3.1 加载fastDFS配置

⭐ 通过ClientGlobal.init(filePath);加载配置

/**
 * FastDFS工具类
 */
public class FastDFSUtils {
    private static Logger logger = LoggerFactory.getLogger(FastDFSUtils.class);

    /**
     * 初始化客户端
     * ClientGlobal.init(filePath): 读取配置文件,并初始化对应的属性
     */

    static {
        try {
            // 获取绝对路径
            String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
            ClientGlobal.init(filePath);
        } catch (Exception e) {
            // 输出到日志
            logger.error("初始化fastDFS失败:", e);
        }
    }

3.2 fastDFS的文件上传

⭐ uploadResults返回的是一个字符串数组: 第一个元素为组名,第二个元素为组下的文件路径

    /**
     * uploadResults是一个字符串数组, 第一个元素是组名, 第二个元素是在该组下文件路径
     * @param file
     * @return
     */
    public static String[] upload(MultipartFile file) {
        String name = file.getOriginalFilename();
        logger.info("文件名:",name);
        StorageClient storageClient = null;
        String[] uploadResults = null;

        try {
            // 获取storage客户端
            storageClient = getStorageClient();
            // 上传
            uploadResults = storageClient.upload_file(file.getBytes(), name.substring(name.lastIndexOf(".")+1),null);

        }catch (Exception e) {
            logger.error("文件上传失败:", e);
        }

        if (null == uploadResults) {
            logger.error("上传失败", storageClient.getErrorCode());
        }

        return uploadResults;
    }

3.3 fastDFS的获取文件信息

    /**
     * 获取文件信息
     * @param groupName
     * @param remoteFileName
     * @return
     */
    public static FileInfo getFileInfo(String groupName, String remoteFileName) {
        StorageClient storageClient = null;
        try {
            storageClient = getStorageClient();
            return storageClient.get_file_info(groupName, remoteFileName);
        }catch (Exception e) {
            logger.error("文件信息获取失败:", e);
        }
        return null;
    }

3.4 fastDFS的文件下载

	/**
     * 下载文件
     * @param groupName
     * @param remoteFileName
     * @return
     */
    public static InputStream downFile(String groupName, String remoteFileName) {
        StorageClient storageClient = null;
        try {
            storageClient = getStorageClient();
            byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
            InputStream inputStream = new ByteArrayInputStream(fileByte);
            return inputStream;
        }catch (Exception e) {
            logger.error("文件下载失败:", e);
        }
        return null;
    }

3.5 fastDFS的文件删除

/**
     * 删除文件
     * @param groupName
     * @param remoteFileName
     */
    public static void deleteFile(String groupName, String remoteFileName) {
        StorageClient storageClient = null;
        try {
            storageClient = getStorageClient();
            storageClient.delete_file(groupName, remoteFileName);
        }catch (Exception e) {
            logger.error("文件删除失败:", e);
        }
    }

3.6 fastDFS的获取storageClient、获取trackerServer

	/**
     * 获取 storageClient
     * @return
     * @throws IOException
     */
    private static StorageClient getStorageClient() throws IOException{
        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = new StorageClient(trackerServer, null);
        return storageClient;
    }


    /**
     * 通过trackerClient客户端获取 trackerServer服务
     * @return
     * @throws IOException
     */
    private static TrackerServer getTrackerServer() throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getTrackerServer();
        return trackerServer;
    }

3.7 fastDFS的获取服务的运行服务器地址

/**
     * 获取文件url
     */

    public static String getTrackerUrl() {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = null;
        StorageServer storageServer = null;
        try {
            trackerServer = trackerClient.getTrackerServer();
            storageServer = trackerClient.getStoreStorage(trackerServer);
        } catch (Exception e) {
            logger.error("文件路径获取失败", e.getMessage());
        }

        return "http://" + storageServer.getInetSocketAddress().getHostString()+":6677/";
    }

3.8 整体文件,点我进行复制

package com.jzq.server.util.fastDFS;

import io.swagger.models.auth.In;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;


/**
 * FastDFS工具类
 */
public class FastDFSUtils {
    private static Logger logger = LoggerFactory.getLogger(FastDFSUtils.class);

    /**
     * 初始化客户端
     * ClientGlobal.init(filePath): 读取配置文件,并初始化对应的属性
     */

    static {
        try {
            // 获取绝对路径
            String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
            ClientGlobal.init(filePath);
        } catch (Exception e) {
            // 输出到日志
            logger.error("初始化fastDFS失败:", e);
        }
    }

    /**
     * uploadResults是一个字符串数组, 第一个元素是组名, 第二个元素是在该组下文件路径
     * @param file
     * @return
     */
    public static String[] upload(MultipartFile file) {
        String name = file.getOriginalFilename();
        logger.info("文件名:",name);
        StorageClient storageClient = null;
        String[] uploadResults = null;

        try {
            // 获取storage客户端
            storageClient = getStorageClient();
            // 上传
            uploadResults = storageClient.upload_file(file.getBytes(), name.substring(name.lastIndexOf(".")+1),null);

        }catch (Exception e) {
            logger.error("文件上传失败:", e);
        }

        if (null == uploadResults) {
            logger.error("上传失败", storageClient.getErrorCode());
        }

        return uploadResults;
    }


    /**
     * 获取文件信息
     * @param groupName
     * @param remoteFileName
     * @return
     */
    public static FileInfo getFileInfo(String groupName, String remoteFileName) {
        StorageClient storageClient = null;
        try {
            storageClient = getStorageClient();
            return storageClient.get_file_info(groupName, remoteFileName);
        }catch (Exception e) {
            logger.error("文件信息获取失败:", e);
        }
        return null;
    }


    /**
     * 下载文件
     * @param groupName
     * @param remoteFileName
     * @return
     */
    public static InputStream downFile(String groupName, String remoteFileName) {
        StorageClient storageClient = null;
        try {
            storageClient = getStorageClient();
            byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
            InputStream inputStream = new ByteArrayInputStream(fileByte);
            return inputStream;
        }catch (Exception e) {
            logger.error("文件下载失败:", e);
        }
        return null;
    }

    /**
     * 删除文件
     * @param groupName
     * @param remoteFileName
     */
    public static void deleteFile(String groupName, String remoteFileName) {
        StorageClient storageClient = null;
        try {
            storageClient = getStorageClient();
            storageClient.delete_file(groupName, remoteFileName);
        }catch (Exception e) {
            logger.error("文件删除失败:", e);
        }
    }


    /**
     * 获取 storageClient
     * @return
     * @throws IOException
     */
    private static StorageClient getStorageClient() throws IOException{
        TrackerServer trackerServer = getTrackerServer();
        StorageClient storageClient = new StorageClient(trackerServer, null);
        return storageClient;
    }


    /**
     * 通过trackerClient客户端获取 trackerServer服务
     * @return
     * @throws IOException
     */
    private static TrackerServer getTrackerServer() throws IOException {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getTrackerServer();
        return trackerServer;
    }


    /**
     * 获取文件url
     */

    public static String getTrackerUrl() {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = null;
        StorageServer storageServer = null;
        try {
            trackerServer = trackerClient.getTrackerServer();
            storageServer = trackerClient.getStoreStorage(trackerServer);
        } catch (Exception e) {
            logger.error("文件路径获取失败", e.getMessage());
        }

        return "http://" + storageServer.getInetSocketAddress().getHostString()+":6677/";
    }
}

四、 上传一个图片具体应用

4.1 controller层

除了更新数据库,还要更新全局对象,所以获取了authentication

@ApiOperation(value = "更新用户头像")
    @PostMapping("/userface")
    public RespBean updateAdminUserFace(MultipartFile multipartFile, Integer id, Authentication authentication) {
        String[] filePath = FastDFSUtils.upload(multipartFile);
        String url = FastDFSUtils.getTrackerUrl() + filePath[0] + "/" + filePath[1];
        return adminService.updateAdminUserFace(url, id, authentication);
    }

4.2 service层

	 /**
     * 更新用户头像
     * @param url
     * @param id
     * @param authentication
     * @return
     */
    @Override
    public RespBean updateAdminUserFace(String url, Integer id, Authentication authentication) {
        Admin admin = adminMapper.selectById(id);
        admin.setUserFace(url);

        // 更新数据库
        int result = adminMapper.updateById(admin);
        if (1==result) {
            //更新数据库成功后要更新全局对象(security)
            Admin principal = (Admin) authentication.getPrincipal();
            principal.setUserFace(url);
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(admin, null, authentication.getAuthorities()));
            return RespBean.success("更新用户头像成功");
        }

        return RespBean.warning("更新用户头像失败");
    }

你可能感兴趣的:(spring,SpringBoot,spring,boot,nginx,java)