JAVA使用-fastDFS的快速上手

在这里插入图片描述

1.导入相关坐标

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

2.yml配置文件

在这里插入图片描述

fastdfs.connect_timeout_in_seconds = 5
fastdfs.network_timeout_in_seconds = 30
fastdfs.charset = UTF-8
fastdfs.tracker_servers = 服务器ip:22122

当配置文件不为Config时

test:
  fastdfs:
    connect_timeout_in_seconds: 5000
    network_timeout_in_seconds: 3000
    charset: UTF-8
    tracker_servers: 服务器ip:22122
    #多个 trackerServer中间以逗号分隔

fastFDS的环境应该这样加载

@Value("${test.fastdfs.tracker_servers}")
String tracker_servers;
@Value("${test.fastdfs.connect_timeout_in_seconds}")
int connect_timeout_in_seconds;
@Value("${test.fastdfs.network_timeout_in_seconds}")
int network_timeout_in_seconds;
@Value("${test.fastdfs.charset}")
String charset;


//加载fdfs的配置
private void initFdfsConfig(){
    try {
        ClientGlobal.initByTrackers(tracker_servers);
        ClientGlobal.setG_connect_timeout(connect_timeout_in_seconds);
        ClientGlobal.setG_network_timeout(network_timeout_in_seconds);
        ClientGlobal.setG_charset(charset);
    } catch (Exception e) {
        e.printStackTrace();
        //初始化文件系统出错
        //用自动异常捕获类抓异常
        ExceptionCast.cast(FileSystemCode.FS_INITFDFSERROR);
    }
}

文件上传

在这里插入图片描述

//文件对象上传
private String uploadFile(MultipartFile multipartFile) {
    try {
        //初始化fastDFS环境,用读取配置文件中信息的方式
        initFdfsConfig();
        //定义TrackerClient,用于请求TrackerService
        TrackerClient trackerClient=new TrackerClient();
        //连接tracker
        TrackerServer trackerServer=trackerClient.getConnection();
        //获取stroage
        StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);
        //创建stroageClient
        StorageClient1 storageClient1=new StorageClient1(trackerServer,storeStorage);
        //像stroage服务器上传文件
        //上传文件
        //文件字节
        byte[] bytes = multipartFile.getBytes();
        //文件原始名称
        String originalFilename = multipartFile.getOriginalFilename();
        //文件扩展名
        String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //第一个参数 文件的字节数组  第二个参数 文件后缀名 第三个参数 文件的原信息
        //上传成功后拿到fileID
        String fileID = storageClient1.upload_file1(bytes, extName, null);
        return fileID;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (MyException e) {
        e.printStackTrace();
    }
    return null;
}

上传文件的测试:

//上传文件测试
@Test
public void UploadTest(){

    try {
       //初始化fastDFS环境,用加载配置文件的方式
        //加载fastdfs-client.properties
        ClientGlobal.initByProperties("config/fastdfs-client.properties");
        //定义TrackerClient,用于请求TrackerService
        TrackerClient trackerClient=new TrackerClient();
        //连接tracker
        TrackerServer trackerServer=trackerClient.getConnection();
        //获取stroage
        StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);
        //创建stroageClient
        StorageClient1 storageClient1=new StorageClient1(trackerServer,storeStorage);
        //像stroage服务器上传文件
        //本地文件的路径
        String filePath="C:/Users/fxh/Pictures/Camera Roll/aaa.png";
        //第一个参数 文件路径  第二个参数 文件后缀名 第三个参数 文件的原信息
        //上传成功后拿到fileID
        String fileID = storageClient1.upload_file1(filePath, "png", null);
        System.out.println(fileID);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (MyException e) {
        e.printStackTrace();
    }

}  

文件下载

在这里插入图片描述

@Test
public void downLoadTest(){
    try {
        //初始化fastDFS环境,用加载配置文件的方式
        //加载fastdfs-client.properties配置文件
        ClientGlobal.initByProperties("config/fastdfs-client.properties");
        //定义TrackerClient,用于请求TrackerServer
        TrackerClient trackerClient = new TrackerClient();
        //连接tracker
        TrackerServer trackerServer = trackerClient.getConnection();
        //获取Stroage
        StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);
        //创建stroageClient
        StorageClient1 storageClient1 = new StorageClient1(trackerServer,storeStorage);
        //下载文件
        //文件id
        String fileId = "group1/M00/00/00/rBEAC14Rqg6ATptRAAydjcS38-4823.png";
        byte[] bytes = storageClient1.download_file1(fileId);
        //使用输出流保存文件
        FileOutputStream fileOutputStream = new FileOutputStream(new File("C:/Users/fxh/Pictures/Camera Roll/ddd.png"));
        fileOutputStream.write(bytes);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (MyException e) {
        e.printStackTrace();
    }
}

文件查询

//    查询文件测试
    @Test
     public void testQueryFile(){
        try {
             //初始化fastDFS环境,用加载配置文件的方式
            //加载fastdfs-client.properties配置文件
            ClientGlobal.initByProperties("config/fastdfs-client.properties");
            //定义TrackerClient,用于请求TrackerServer
            TrackerClient trackerClient = new TrackerClient();
            //连接tracker
            TrackerServer trackerServer = trackerClient.getConnection();
//            StorageServer storageServer=null;
//            StorageClient1 storageClient1 = new StorageClient1(trackerServer,storageServer);
//            FileInfo fileInfo = storageClient1.query_file_info("group1", "M00/00/00/rBEAC14Rqg6ATptRAAydjcS38-4823.png");
            //获取Stroage
            StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);
            //创建stroageClient
            StorageClient1 storageClient1 = new StorageClient1(trackerServer,storeStorage);
            FileInfo fileInfo = storageClient1.query_file_info1("group1/M00/00/00/rBEAC14Rqg6ATptRAAydjcS38-4823.png");
            System.out.println(fileInfo);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
    }

上面如果觉得太麻烦 这里还有简单的写法

fastDFS 使用(基于springboot)

1、导入依赖

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

2、创建一个fastDFS配置类

@Configuration
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration= RegistrationPolicy.IGNORE_EXISTING)
public class FastDFSConfiguration {
}

在这里插入图片描述

3.application.yml 中配置fastdfs信息:

fdfs:
  ## tracker地址
  trackerList: 服务器ip:22122
  ## 连接超时时间
  connect-timeout: 5000
  ## 读取inputsream阻塞时间
  so-timeout: 3000
  pool:
    ## 连接池最大数量
    max-total: 200
    ## 每个tracker地址的最大连接数
    max-total-per-key: 20
    ## 连接耗尽时等待获取连接的最大毫秒数
    max-wait-millis: 25000

4、在工程中加入fastdfs工具类:

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

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

@Component
public class FastDFSClientWrapper {
    @Autowired
    private FastFileStorageClient storageClient;

    /**
     * @Description: 上传文件
     * @param file 文件对象
     * @return 文件路径ID
     * @throws IOException
     */
    public String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()), null);
        return storePath.getFullPath();
    }

    /**
     * @Description: 上传文件
     * @param bytes 文件数据
     * @param format 文件格式(后缀)
     * @return String 文件路径ID
     */
    public String uploadFile(byte[] bytes, String format) {
        StorePath storePath = storageClient.uploadFile(new ByteArrayInputStream(bytes), bytes.length, format, null);
        return storePath.getFullPath();
    }

    /**
     * @Description: 上传文件
     * @param file 文件对象
     * @return   文件路径ID
     * @throws IOException
     */
    public String uploadFile(File file) throws IOException {
        StorePath storePath = storageClient.uploadFile(FileUtils.openInputStream(file), file.length(),
                FilenameUtils.getExtension(file.getName()), null);
        return storePath.getFullPath();
    }


    /**
     * @Description: 根据文件路径下载文件
     * @param filePath 文件路径
     * @return 文件字节数据
     * @throws IOException
     */
    public byte[] downFile(String filePath) throws IOException {
        StorePath storePath = StorePath.parseFromUrl(filePath);
        return storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadCallback<byte[]>() {
            @Override
            public byte[] recv(InputStream ins) throws IOException {
                return org.apache.commons.io.IOUtils.toByteArray(ins);
            }
        });
    }

    /**
     * @Description: 根据文件地址删除文件
     * @param filePath 文件访问地址
     */
    public void deleteFile(String filePath) {
        StorePath storePath = StorePath.parseFromUrl(filePath);
        storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
    }

}

5、使用fastdfs-client文件上传操作

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值