FastDFS使用

本文详细介绍如何使用FastDFS进行文件上传操作,包括配置文件的设置、依赖导入、Java代码实现及工具类封装,同时提供了应用配置与具体上传过程的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

1、导入坐标

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

 

2、配置fdfs_client.conf配置文件

# connect timeout in seconds
# default value is 30s
connect_timeout=30
​
# network timeout in seconds
# default value is 30s
network_timeout=60
​
# the base path to store log files
# FastDFS安装位置
base_path=/home/fastdfs
​
# tracker_server can ocur more than once, and tracker_server format is
#  "host:port", host can be hostname or ip address
# Tracker Server服务器IP地址和端口号(默认端口号:22122)
tracker_server=192.168.25.133:22122
​
#standard log level as syslog, case insensitive, value list:
### emerg for emergency
### alert
### crit for critical
### error
### warn for warning
### notice
### info
### debug
log_level=info
​
# if use connection pool
# default value is false
# since V4.05
use_connection_pool = false
​
# connections whose the idle time exceeds this time will be closed
# unit: second
# default value is 3600
# since V4.05
connection_pool_max_idle_time = 3600
​
# if load FastDFS parameters from tracker server
# since V4.05
# default value is false
load_fdfs_parameters_from_tracker=false
​
# if use storage ID instead of IP address
# same as tracker.conf
# valid only when load_fdfs_parameters_from_tracker is false
# default value is false
# since V4.05
use_storage_id = false
​
# specify storage ids filename, can use relative or absolute path
# same as tracker.conf
# valid only when load_fdfs_parameters_from_tracker is false
# since V4.05
storage_ids_filename = storage_ids.conf
​
​
#HTTP settings
http.tracker_server_port=80
​
#use "#include" directive to include HTTP other settiongs
##include http.conf

 

3、Java代码

package cn.itcast.test;
​
import org.csource.fastdfs.*;
import sun.applet.Main;
​
public class FastDFSTest {
​
    public static void main(String[] args) throws Exception {
        // 1、 加载配置文件
        // ClientGlobal.init():fastdfs中专门用来加载配置文件
        ClientGlobal.init("C:\\itcast68\\fastDFSDemo\\src\\main\\resources\\fdfs_client.conf");
​
        // 2、 创建一个 TrackerClient 对象。 直接 new 一个。
        TrackerClient client = new TrackerClient();
​
        // 3、 使用 TrackerClient 对象创建连接, 获得一个 TrackerServer 对象。
        TrackerServer server = client.getConnection();
​
        // 4、 创建一个 StorageServer 的引用, 值为 null
        StorageServer storageServer = null;
​
        // 5、 创建一个 StorageClient 对象, 需要两个参数 TrackerServer 对象、 StorageServ
        // er的引用
        StorageClient storageClient = new StorageClient(server, storageServer);
        
        // 6、 使用 StorageClient 对象上传图片。
        // 参数1: 需要上传的文件的绝对路径。
        // 参数2:需要上传的文件的类型(用来区分文件上传到那个StorageServer组中,实际中需要动态获取)
        // 参数3:文件的详细信息
        String[] strings = storageClient.upload_file("D:\\desktop\\image\\02.jpg", "jpg", null);
​
        // 7、 返回数组。 包含组名和图片的路径。
        // strings[0]:组名
        // strings[1]: 路径
        for (String string : strings) {
            System.out.println(string);
        }
    }
}

 

2、Fast DFS工具类

1、工具类代码

package util;
​
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
​
public class FastDFSClient {
​
    private TrackerClient trackerClient = null;
    private TrackerServer trackerServer = null;
    private StorageServer storageServer = null;
    private StorageClient1 storageClient = null;
    
    // 构造函数,创建时需要指定fdfs_client.conf配置文件的位置,与TrackerServer建立连接
    public FastDFSClient(String conf) throws Exception {
        if (conf.contains("classpath:")) {
            conf = conf.replace("classpath:", this.getClass().getResource("/").getPath());
        }
        ClientGlobal.init(conf);
        trackerClient = new TrackerClient();
        trackerServer = trackerClient.getConnection();
        storageServer = null;
        storageClient = new StorageClient1(trackerServer, storageServer);
    }
    
    /**
     * 上传文件方法
     * <p>Title: uploadFile</p>
     * <p>Description: </p>
     * @param fileName 文件全路径
     * @param extName 文件扩展名,不包含(.)
     * @param metas 文件扩展信息
     * @return
     * @throws Exception
     */
    public String uploadFile(String fileName, String extName, NameValuePair[] metas) throws Exception {
        String result = storageClient.upload_file1(fileName, extName, 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);
    }
    
    /**
     * 上传文件方法
     * <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);
    }
}

 

2、实现文件上传

applaction.properties配置文件

# TrackerServer服务器IP地址
FILE_SERVER_URL=http://192.168.25.133/

java代码

package com.pinyougou.shop.controller;
​
import com.pinyougou.sellergoods.service.GoodsDescService;
import entity.Result;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import util.FastDFSClient;
​
/**
 * @author Hxc@hongxiancheng.com
 * @date 2018/11/24 11:04
 */
@RestController
@RequestMapping("/fastDFS")
public class UploadController {
    @Value("${FILE_SERVER_URL}")
    private String file_url; // TrackerServer服务器IP地址
​
    // 文件上传
    @RequestMapping("/upload")
    public Result upload(MultipartFile file) {
        try {
            // 获取文件名称
            String fileName = file.getOriginalFilename();
            // 获取文件类型
            String type = fileName.substring(fileName.lastIndexOf(".") + 1); 
​
            // 获取FasdDFS工具类对象
            FastDFSClient fastDFSClient = new FastDFSClient("classpath:config/fdfs_client.conf");
            
            // 上传文件,返回file_id
            // 参数1:需要上传的文件,使用二进制形式(网络传输)
            // 参数2:文件类型,扩展名
            String fileId = fastDFSClient.uploadFile(file.getBytes(), type);// 上传文件
            
            // 返回trackerServer服务器IP地址和file_id,或者保存到本地数据库
            return new Result(true, FILE_SERVER_URL + fileId);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "上传失败");
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值