风止雨歇

Fastdfs 上传图片

一、fastdfs-client的jar包导入

1、下载地址:https://github.com/happyfish100/fastdfs-client-java

2、将代码使用git下载下来之后,使用源码安装;

mvn clean install

3、安装成功后,在项目的pom.xml文件中使用如下坐标引入;

<dependency>
    <groupId>org.csource</groupId>
    <artifactId>fastdfs-client-java</artifactId>
    <version>1.27-SNAPSHOT</version>
</dependency>

 

二、配置fastdfs的配置文件

1、在引入的jar包中查找配置文件,下图中的为例子(配置文件以.conf 或 .prpperties 结尾

 注:本帖子使用 .conf 作为配置文件;

2、在 classpath 路径下创建 fdfs_client.conf 文件,并将上图中的 fdfs_client.conf.sample文件内容拷贝到该文件中,修改配置文件中的 tracker_server 为指定的fastdfs主机的IP;

注1:tracker_server指向您自己IP地址和端口,1-n个
注2:除了tracker_server,其它配置项都是可选的

 

 三、连接fastdfs分布式文件系统

FastDfsUtils.java

import org.apache.commons.io.FilenameUtils;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;
import org.springframework.core.io.ClassPathResource;

/**
 * 连接fastdfs, 上传图片
 * 返回上传的路径, 例如: group1/M00/00/00/wKisFFpBG9eAHaQvAAAWKd1hQR4158_big.jpg
 * @author pc
 *
 */
public class FastDfsUtils
{
    //上传图片
    public static String uploadPic(byte[] pic, String name, long size) throws Exception
    {
        //读取配置文件
        ClassPathResource resource = new ClassPathResource("fdfs_client.conf"); //从classpath路径下读取文件
        ClientGlobal.init(resource.getClassLoader().getResource("fdfs_client.conf").getPath());
        
        //连接tracker的客户端
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection(); 
        
        //连接storage的客户端
        StorageServer storageServer = null;
        StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);
        
        //上传图片
        String ext = FilenameUtils.getExtension(name);  //获取扩展名
        NameValuePair[] metaArr = new NameValuePair[3]; //描述信息
        metaArr[0] = new NameValuePair("fileName", name);
        metaArr[1] = new NameValuePair("fileExt", ext);
        metaArr[2] = new NameValuePair("fileSize", String.valueOf(size));
        
        String path = storageClient1.upload_file1(pic, ext, metaArr); //返回存储的文件路径
        return path;
    }
}

注:StorageClient1 为升级版本的, upload_file1(byte[], String, NameValuePair[]) 为升级版的方法;

 

posted on 2018-01-06 19:38  风止雨歇  阅读(3286)  评论(0编辑  收藏  举报

导航