fastdfs02-springboot加入FastDFS工具类

fastdfs相关

1、fastdfs01-Linux下安装fastdfs(tracker和storage安装): https://blog.csdn.net/xixiyuguang/article/details/105160807

2、fastdfs02-创建springboot进行连接fastdfs:https://blog.csdn.net/xixiyuguang/article/details/105161424

fastdfs01-FastDFS-配置token教程及问题:https://blog.csdn.net/xixiyuguang/article/details/104772505

fastdfs02-springboot加入FastDFS工具类: https://blog.csdn.net/xixiyuguang/article/details/105142448

 

 

 

代码目录截图

1、maven依赖

<!-- https://mvnrepository.com/artifact/net.oschina.zcx7878/fastdfs-client-java -->
        <dependency>
            <groupId>net.oschina.zcx7878</groupId>
            <artifactId>fastdfs-client-java</artifactId>
            <version>1.27.0.0</version>
        </dependency>

2、配置文件fastdfs-client.properties

## fastdfs-client.properties

fastdfs.connect_timeout_in_seconds = 5
fastdfs.network_timeout_in_seconds = 30

fastdfs.charset = UTF-8

fastdfs.http_anti_steal_token = false
fastdfs.http_secret_key = FastDFS1234567890
fastdfs.http_tracker_http_port = 80

#fastdfs.tracker_servers = 10.0.11.201:22122,10.0.11.202:22122,10.0.11.203:22122
fastdfs.tracker_servers = 192.168.116.128:22122

## Whether to open the connection pool, if not, create a new connection every time
fastdfs.connection_pool.enabled = true

## max_count_per_entry: max connection count per host:port , 0 is not limit
fastdfs.connection_pool.max_count_per_entry = 500

## connections whose the idle time exceeds this time will be closed, unit: second, default value is 3600
fastdfs.connection_pool.max_idle_time = 3600

## Maximum waiting time when the maximum number of connections is reached, unit: millisecond, default value is 1000
fastdfs.connection_pool.max_wait_time_in_ms = 1000

 

3、工具类代码

package com.yg.springboot.util;

import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author yuguang
 * @date 2020/3/24 16:01
 * @desc
 */
public class FastDFSUtil {
    static Logger logger = LoggerFactory.getLogger(FastDFSUtil.class);

    static {
        try {
            ClientGlobal.initByProperties("fastdfs-client.properties");
        } catch (Exception e) {
            logger.error("FastFds初始化失败", e);
        }
    }

    //文件上传
    public String upload(MultipartFile file) throws Exception {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();

        StorageServer storageServer = null;
        StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);

        NameValuePair pairs[] = null;
        String oldName = file.getOriginalFilename();
        //扩展名
        String extName = oldName.substring(oldName.lastIndexOf(".") + 1);
        String file1 = storageClient1.upload_file1(file.getBytes(), extName, pairs);
        return file1;
    }

    /**
     * 上传到服务器
     *
     * @param localFilePath 本地文件全路径
     * @return
     */
    public String[] fileLocalUpload(String localFilePath) {
        return fileLocalUpload(localFilePath, null);
    }

    /**
     * 上传到服务器
     *
     * @param localFilePath 本地文件全路径
     * @param nvp           NameValuePair
     * @return
     */
    public String[] fileLocalUpload(String localFilePath, NameValuePair[] nvp) {
        try {
            TrackerClient tracker = new TrackerClient();
            TrackerServer trackerServer = tracker.getConnection();
            StorageServer storageServer = null;
            StorageClient storageClient = new StorageClient(trackerServer, storageServer);
            //文件拓展名
            String fileExtName = localFilePath.substring(localFilePath.lastIndexOf(".") + 1);
            String fileIds[] = storageClient.upload_file(localFilePath, fileExtName, nvp);

            logger.info("fileIds.length={}", fileIds.length);
            logger.info("组名={}", fileIds[0]);
            logger.info("路径={} ", fileIds[1]);
            return fileIds;
        } catch (FileNotFoundException e) {
            logger.error("FastFds上传失败", e);
        } catch (IOException e) {
            logger.error("FastFds上传失败", e);
        } catch (MyException e) {
            logger.error("FastFds上传失败", e);
        }
        return null;
    }

    /**
     * 从文件服务器下载
     *
     * @param remoteFilename 文件名称例如: M00/00/00/wKgqHVty2ZCAHaBvAAE0vHMtwgw608.png
     * @return
     */
    public boolean fileServerDownload(String remoteFilename) {
        return fileServerDownload("group1", remoteFilename, System.getProperty("java.io.tmpdir") + UUID.randomUUID().toString() + ".tmp");
    }

    /**
     * 从文件服务器下载
     *
     * @param remoteFilename    服务器文件名称例如: M00/00/00/wKgqHVty2ZCAHaBvAAE0vHMtwgw608.png
     * @param localDownloadPath 下载到本地路径
     * @return
     */
    public boolean fileServerDownload(String remoteFilename, String localDownloadPath) {
        return fileServerDownload("group1", remoteFilename, localDownloadPath);
    }

    /**
     * 从文件服务器下载
     *
     * @param groupName         组名
     * @param remoteFilename    服务器文件名称例如: M00/00/00/wKgqHVty2ZCAHaBvAAE0vHMtwgw608.png
     * @param localDownloadPath 下载到本地路径
     * @return
     */
    public boolean fileServerDownload(String groupName, String remoteFilename, String localDownloadPath) {
        try {
            TrackerClient tracker = new TrackerClient();
            TrackerServer trackerServer = tracker.getConnection();
            StorageServer storageServer = null;
            StorageClient storageClient = new StorageClient(trackerServer, storageServer);
            byte[] b = storageClient.download_file(groupName, remoteFilename);
            FileOutputStream fos = new FileOutputStream(new File(localDownloadPath));
            fos.write(b);
            fos.close();

            return true;
        } catch (Exception e) {
            logger.error("FastFds下载失败", e);
            return false;
        }
    }

    /**
     * 获取文件信息
     *
     * @param remoteFilename 服务器文件名称例如: M00/00/00/wKgqHVty2ZCAHaBvAAE0vHMtwgw608.png
     * @return
     */
    public FileInfo getFileInfo(String remoteFilename) {
        return getFileInfo("group1", remoteFilename);
    }

    /**
     * 获取文件信息
     *
     * @param groupName      组名
     * @param remoteFilename 服务器文件名称例如: M00/00/00/wKgqHVty2ZCAHaBvAAE0vHMtwgw608.png
     * @return
     */
    public FileInfo getFileInfo(String groupName, String remoteFilename) {
        try {
            TrackerClient tracker = new TrackerClient();
            TrackerServer trackerServer = tracker.getConnection();
            StorageServer storageServer = null;
            StorageClient storageClient = new StorageClient(trackerServer, storageServer);
            FileInfo fi = storageClient.get_file_info(groupName, remoteFilename);
            System.out.println(fi.getSourceIpAddr());
            System.out.println(fi.getFileSize());
            System.out.println(fi.getCreateTimestamp());
            System.out.println(fi.getCrc32());
            return fi;
        } catch (Exception e) {
            logger.error("FastFds获取文件信息失败", e);
            return null;
        }
    }

    public NameValuePair[] getFileMate(String remoteFilename) {
        return getFileMate("group1", remoteFilename);
    }

    public NameValuePair[] getFileMate(String groupName, String remoteFilename) {
        try {
            TrackerClient tracker = new TrackerClient();
            TrackerServer trackerServer = tracker.getConnection();
            StorageServer storageServer = null;
            StorageClient storageClient = new StorageClient(trackerServer, storageServer);
            NameValuePair nvps[] = storageClient.get_metadata(groupName, remoteFilename);
            for (NameValuePair nvp : nvps) {
                System.out.println(nvp.getName() + ":" + nvp.getValue());
            }
            return nvps;
        } catch (Exception e) {
            logger.error("FastFds获取文件描述信息失败", e);
            return null;
        }
    }

    /**
     * 删除服务器文件
     *
     * @param remoteFilename 服务器文件名称例如: M00/00/00/wKgqHVty2ZCAHaBvAAE0vHMtwgw608.png
     * @return
     */
    public boolean delete(String remoteFilename) {
        return delete("group1", remoteFilename);
    }

    /**
     * 删除服务器文件
     *
     * @param groupName      组名
     * @param remoteFilename 服务器文件名称例如: M00/00/00/wKgqHVty2ZCAHaBvAAE0vHMtwgw608.png
     * @return
     */
    public boolean delete(String groupName, String remoteFilename) {
        try {
            TrackerClient tracker = new TrackerClient();
            TrackerServer trackerServer = tracker.getConnection();
            StorageServer storageServer = null;
            StorageClient storageClient = new StorageClient(trackerServer, storageServer);
            int i = storageClient.delete_file("group1", remoteFilename);
            logger.info(i == 0 ? "删除成功" : "删除失败:" + i);
            return i == 0 ? true : false;
        } catch (Exception e) {
            logger.error("FastFds删除失败", e);
            return false;
        }
    }

    public static void main(String[] args) {
        FastDFSUtil fastFdsTest = new FastDFSUtil();
        String[] strings = fastFdsTest.fileLocalUpload("D:\\header.jpg");

        //获取文件信息
        FileInfo ll = fastFdsTest.getFileInfo(strings[1]);

        //下载图片到本地
        boolean fl = fastFdsTest.fileServerDownload("group1", strings[1], "D:\\" + UUID.randomUUID() + "test.png");

        //删除文件
        boolean fla = fastFdsTest.delete(strings[1]);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值