spring boot集成fastDFS以及入门小Demo(三)

fastDFS简介(一)
fastDFS服务器的安装(二)
spring boot集成fastDFS以及入门小Demo(三)
fastDFS异常的处理(四)



一、入门小Demo

1、pom依赖

    <dependencies>
        <dependency>
            <groupId>org.csource.fastdfs</groupId>
            <artifactId>fastdfs</artifactId>
            <version>1.2</version>
        </dependency>

2、Demo

public class TestFastDFS {

    public static void main(String[] args) throws Exception {
        //1. 加载配置文件
        ClientGlobal.init("D:\\fdfs_client.conf");
        //2. 创建管理端对象
        TrackerClient trackerClient = new TrackerClient();
        //3. 获取连接
        TrackerServer connection = trackerClient.getConnection();
        //4. 创建存储端对象
        StorageClient1 storageClient = new StorageClient1(connection, null);

        //创建文件属性信息数组
        NameValuePair[] meta_list = new NameValuePair[3];
        meta_list[0] = new NameValuePair("filename","Koala.jpg");
        meta_list[1] = new NameValuePair("ext","jpg");
        meta_list[2] = new NameValuePair("auth","zj");
        //5. 上传
        //上传后的路径例如: group1/M00/00/01/wKjIgFzGdyuABc7WAAvqH_kipG8074.jpg
        String path = storageClient.upload_file1("D:\\dog.jpg", "jpg", meta_list);
        System.out.println("========" + path);
    }
}

二、spring boot集成fastDFS

1、pom依赖

        <dependency>
            <groupId>net.oschina.zcx7878</groupId>
            <artifactId>fastdfs-client-java</artifactId>
            <version>1.27.0.0</version>
        </dependency>

2、 fastDFS配置文件

# 连接超时(默认30s)
connect_timeout=30

# 网络超时(默认值为30s)
network_timeout=60

# 存储日志文件的基本路径
base_path=/home/fastdfs

# 上传文件的地址
tracker_server=192.168.200.128:22122

# 作为syslog的标准日志级别(默认info)
log_level=info

# 如果使用连接池(默认为false)
use_connection_pool = false

# 最大空闲连接时间(默认为3600)
connection_pool_max_idle_time = 3600

# 如果FastDFS的参数来自于tracker server(默认为false)
load_fdfs_parameters_from_tracker=false

# 如果使用存储ID而不是IP地址(默认为false)
use_storage_id = false

# 指定存储的文件名
# 当load_fdfs_parameters_from_tracker 为false时使用;
storage_ids_filename = storage_ids.conf

#下载的端口
http.tracker_server_port=80

3、FastDFSClient(通用上传封装类)

3.1、使用配置文件创建连接(入参:classpath:fastDFS/fdfs_client.properties)

//        获取fastDFS配置文件的绝对路径
        if (conf.contains("classpath:")) {
            conf = conf.replace("classpath:", this.getClass().getResource("/").getPath());
        }
//        加载配置文件
        ClientGlobal.init(conf);

3.2、使用配置文件创建连接(入参:classpath:fastDFS/fdfs_client.properties)

跟踪配置文件的位置器
在这里插入图片描述

//        1.2、使用fastDFS地址创建连接(入参:192.168.200.128:22122)
        Properties pro = new Properties();
        pro.setProperty("fastdfs.tracker_servers", conf);
        ClientGlobal.initByProperties(pro);

封装的FastDFSClient

import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Properties;

public class FastDFSClient {

    private TrackerClient trackerClient = null;
    private TrackerServer trackerServer = null;
    private StorageServer storageServer = null;
    private StorageClient1 storageClient = null;

//    初始化创建FastDFS连接
    public FastDFSClient(String conf) throws Exception {
//        1.1、使用配置文件创建连接(入参:classpath:fastDFS/fdfs_client.properties)
//        获取fastDFS配置文件的绝对路径
        if (conf.contains("classpath:")) {
            conf = conf.replace("classpath:", this.getClass().getResource("/").getPath());
        }
//        加载配置文件
        ClientGlobal.init(conf);
//        1.2、使用fastDFS地址创建连接(入参:192.168.200.128:22122)
//        Properties pro = new Properties();
//        pro.setProperty("fastdfs.tracker_servers", conf);
//        ClientGlobal.initByProperties(pro);

//        2、最终创建storegeClient连接
        trackerClient = new TrackerClient();
        trackerServer = trackerClient.getConnection();
        storageServer = null;
        storageClient = new StorageClient1(trackerServer, storageServer);
    }

    /**
     * 上传文件方法—1
     * <p>Title: uploadFile</p>
     * <p>Description: </p>
     *
     * @param fileName 文件全路径
     * @param extName  文件扩展名,不包含(.)
     * @param metas    文件扩展信息
     */
    public String uploadFile(String fileName, String extName, NameValuePair[] metas) throws Exception {
        String result = storageClient.upload_file1(fileName, extName, metas);
        return result;
    }

    //推荐使用
    public String uploadFile(byte[] file, String fileName, long fileSize) throws Exception {
        NameValuePair[] metas = new NameValuePair[3];
        metas[0] = new NameValuePair("fileName", fileName);
        metas[1] = new NameValuePair("fileSize", String.valueOf(fileSize));
        String result = storageClient.upload_file1(file, fileName, metas);
        return result;
    }

    public String uploadFile(String fileName) throws Exception {
        return uploadFile(fileName, null, null);
    }

    public String uploadFile(String fileName, String extName) throws Exception {
        return uploadFile(fileName, extName, null);
    }

    /**
     * 上传文件方法—2
     * <p>Title: uploadFile</p>
     * <p>Description: </p>
     *
     * @param fileContent 文件的内容,字节数组
     * @param extName     文件扩展名
     * @param metas       文件扩展信息
     * @return
     * @throws Exception
     */
    public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throws Exception {

        String result = storageClient.upload_file1(fileContent, extName, metas);
        return result;
    }

    public String uploadFile(byte[] fileContent) throws Exception {
        return uploadFile(fileContent, null, null);
    }

    public String uploadFile(byte[] fileContent, String extName) throws Exception {
        return uploadFile(fileContent, extName, null);
    }


    //关闭资源
    public void close() throws Exception {
        trackerServer.close();
    }


    /**
     *     //下载1
     * @param groupName         组名
     * @param remoteFileName    文件名
     * @return  返回字节输入流
     * @throws Exception
     */
    public InputStream downloadFile2(String groupName, String remoteFileName) throws Exception {

        byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
        InputStream ins = new ByteArrayInputStream(fileByte);
        return ins;
    }


    /**
     * 下载2
     * @param groupName         组名
     * @param remoteFileName    文件名
     * @return  返回字节数组累心
     * @throws Exception
     */
    public byte[] downloadFile(String groupName, String remoteFileName) throws Exception {

        return storageClient.download_file(groupName, remoteFileName);
    }

//        查询fastDFS服务器中的文件的详细信息(可用来查看是否有当前文件)
    public FileInfo queryFile(String group, String fileName) throws Exception {
        FileInfo fileInfo = storageClient.query_file_info(group, fileName);
        return fileInfo;
    }
}

4、上传代码

    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/uploadFile")
    public ApiResult uploadFile(MultipartFile file) throws Exception {
        try {
            //创建上传工具类对象, 指定配置文件位置
            FastDFSClient fastDFS = new FastDFSClient("classpath:fastDFS/fdfs_client.properties");
            //上传并返回上传后的路径和文件名
            //例如: group1/M00/00/01/wKjIgFzGdyuABc7WAAvqH_kipG8074.jpg
            String path = fastDFS.uploadFile(file.getBytes(), file.getOriginalFilename(), file.getSize());
            //返回上传成功的文件路径和文件名
            return ApiResult.succ(path);
//            return new ApiResult(true, path);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.fail(105, "上传失败");
//            return new Result(false, "上传失败!");
        }
    }

5、下载代码

    /**
     * 下载文件(写出数组)
     * @param groupName
     * @param remoteFileName
     * @return
     * @throws Exception
     */
    @RequestMapping("/downloadFile")
    public byte[]  downloadFile(String groupName, String remoteFileName) throws Exception {
        //创建上传工具类对象, 指定配置文件位置
        FastDFSClient fastDFS = new FastDFSClient("classpath:fastDFS/fdfs_client.properties");

        byte[] bytes = fastDFS.downloadFile(groupName, remoteFileName);
        return bytes;
    }

    /**
     * 下载文件(返回文件数据)
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping("/downloadFile2")
    public void   downloadFile2(HttpServletResponse response, HttpServletRequest request) throws Exception {
//        1、创建fastDFS连接
        FastDFSClient fastDFS = new FastDFSClient("classpath:fastDFS/fdfs_client.properties");
//        2、从请求中获取文件路径和名称
        String groupName = request.getParameter("groupName");
        String remoteFileName = request.getParameter("remoteFileName");
//        3、下载文件数据
        byte[] bytes = fastDFS.downloadFile(groupName, remoteFileName);
//        4、写出文件内容
        ServletOutputStream out = response.getOutputStream();
        InputStream is = new ByteArrayInputStream(bytes);
        byte[] buff = new byte[1024];
        int len = 0;
        while((len=is.read(buff))!=-1){
            out.write(buff, 0, len);
        }
        is.close();
        out.close();
    }

6、查看文件信息代码

   /**
     * 查看文件的信息(用来检测文件是否存在)
     * @param groupName
     * @param remoteFileName
     * @return
     * @throws Exception
     */
    @RequestMapping("/checkFile")
    public ApiResult checkFile(String groupName, String remoteFileName) throws Exception {
        //创建上传工具类对象, 指定配置文件位置
        FastDFSClient fastDFS = new FastDFSClient("classpath:fastDFS/fdfs_client.properties");

        try {
            FileInfo fileInfo = fastDFS.queryFile(groupName, remoteFileName);
            logger.info("查询出来的结果为" + fileInfo.toString());
//            return fileInfo;
        } catch (Exception e) {
            logger.info("没有查询到指定文件的信息");
            return null;
        } finally {
//            关闭连接
            fastDFS.close();
        }
        return null;
    }

7、测试类完整代码

import com.lydms.common.ApiResult;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.csource.fastdfs.FileInfo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

public class TestFastDfs {

    private static final Logger logger = LogManager.getLogger(TestFastDfs.class);

    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/uploadFile")
    public ApiResult uploadFile(MultipartFile file) throws Exception {
        try {
            //创建上传工具类对象, 指定配置文件位置
            FastDFSClient fastDFS = new FastDFSClient("classpath:fastDFS/fdfs_client.properties");
            //上传并返回上传后的路径和文件名
            //例如: group1/M00/00/01/wKjIgFzGdyuABc7WAAvqH_kipG8074.jpg
            String path = fastDFS.uploadFile(file.getBytes(), file.getOriginalFilename(), file.getSize());
            //返回上传成功的文件路径和文件名
            return ApiResult.succ(path);
//            return new ApiResult(true, path);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.fail(105, "上传失败");
//            return new Result(false, "上传失败!");
        }
    }

    /**
     * 下载文件(写出数组)
     * @param groupName
     * @param remoteFileName
     * @return
     * @throws Exception
     */
    @RequestMapping("/downloadFile")
    public byte[]  downloadFile(String groupName, String remoteFileName) throws Exception {
        //创建上传工具类对象, 指定配置文件位置
        FastDFSClient fastDFS = new FastDFSClient("classpath:fastDFS/fdfs_client.properties");

        byte[] bytes = fastDFS.downloadFile(groupName, remoteFileName);
        return bytes;
    }

    /**
     * 下载文件(返回文件数据)
     * @param response
     * @param request
     * @throws Exception
     */
    @RequestMapping("/downloadFile2")
    public void   downloadFile2(HttpServletResponse response, HttpServletRequest request) throws Exception {
//        1、创建fastDFS连接
        FastDFSClient fastDFS = new FastDFSClient("classpath:fastDFS/fdfs_client.properties");
//        2、从请求中获取文件路径和名称
        String groupName = request.getParameter("groupName");
        String remoteFileName = request.getParameter("remoteFileName");
//        3、下载文件数据
        byte[] bytes = fastDFS.downloadFile(groupName, remoteFileName);
//        4、写出文件内容
        ServletOutputStream out = response.getOutputStream();
        InputStream is = new ByteArrayInputStream(bytes);
        byte[] buff = new byte[1024];
        int len = 0;
        while((len=is.read(buff))!=-1){
            out.write(buff, 0, len);
        }
        is.close();
        out.close();
    }

    /**
     * 查看文件的信息(用来检测文件是否存在)
     * @param groupName
     * @param remoteFileName
     * @return
     * @throws Exception
     */
    @RequestMapping("/checkFile")
    public ApiResult checkFile(String groupName, String remoteFileName) throws Exception {
        //创建上传工具类对象, 指定配置文件位置
        FastDFSClient fastDFS = new FastDFSClient("classpath:fastDFS/fdfs_client.properties");

        try {
            FileInfo fileInfo = fastDFS.queryFile(groupName, remoteFileName);
            logger.info("查询出来的结果为" + fileInfo.toString());
//            return fileInfo;
        } catch (Exception e) {
            logger.info("没有查询到指定文件的信息");
            return null;
        } finally {
//            关闭连接
            fastDFS.close();
        }
        return null;
    }

}
posted @ 2019-09-21 17:22  ah_lydms  阅读(171)  评论(0编辑  收藏  举报