ubntu下单机配置fastdfs作为开发环境(4)---将 fastdfs客户端整合到现有java项目中

前言

话说,起初还觉得fastdfs的配置及整合会很简单。。结果不是的。单单篇幅已经有四篇文章了。

正题:
请参考:

关于FastDFS蛋疼的集群和负载均衡(九)之创建FastDFS的Maven项目

这一系列文章有意思。

FastDFS java client SDK

在这里插入图片描述

注意。。。

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

这个是没办法用的,因为,我在gradle上面是broken path,找不到这玩意。。

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

好了,下面这个链接能绑到我们:
FastDFS Client Java » 1.27-RELEASE

<!-- https://mvnrepository.com/artifact/cn.bestwu/fastdfs-client-java -->
<dependency>
    <groupId>cn.bestwu</groupId>
    <artifactId>fastdfs-client-java</artifactId>
    <version>1.27</version>
</dependency>


这是从fork出来的jar拿过来的。

在这里插入图片描述

在这里插入图片描述

起码能用了。

fastDFS与Java整合上传下载

整合过程

1、采用了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 = tw-server:22122,10.0.11.202:22122,10.0.11.203:22122
fastdfs.tracker_servers = tw-server:22122

其他文件:

package net.w2p.DevBase.plugins;

import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.URL;
import java.util.Properties;

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.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

/**
 * @ClassName FastDFSUtils
 * @Description FastDFS工具类
 * @author zhangkai
 * @date 2017年7月18日
 */
public class FastDFSPlugin implements Serializable{
    /**
     *
     */
    private static final long serialVersionUID = -4462272673174266738L;
    private static TrackerClient trackerClient;
    private static TrackerServer trackerServer;
    private static StorageClient1 storageClient1;
    private static Properties config;

    static {
        config=new Properties();
        InputStream inputStream=null;
        try{
            InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("conf/fdfs_client.properties");
            InputStreamReader is=new InputStreamReader(in,"utf-8");
            config.load(is);
            is.close();
            in.close();
        }
        catch (Exception ed){
            ed.printStackTrace();
        }
        try {
//            ClientGlobal.init(resource.getClassLoader().getResource("conf/fdfs_client.conf").getPath());
            //-_- 没办法,原本的框架是web,app两用的,没办法简单粗暴用一个file path来指定文件路径的。

            ClientGlobal.initByProperties(config);
            //trackerclient
            trackerClient = new TrackerClient();
            trackerServer = trackerClient.getConnection();
            //storageclient
            storageClient1 = new StorageClient1(trackerServer,null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * fastDFS文件上传
     * @param file 上传的文件 FastDFSFile
     * @return String 返回文件的绝对路径
     */
    public static String uploadFile(FastDFSFile file){
        String path = null;
        try {
            //文件扩展名
            String ext = FilenameUtils.getExtension(file.getName());
            //mata list是表文件的描述
            NameValuePair[] mata_list = new NameValuePair[3];
            mata_list[0] = new NameValuePair("fileName",file.getName());
            mata_list[1] = new NameValuePair("fileExt",ext);
            mata_list[2] = new NameValuePair("fileSize",String.valueOf(file.getSize()));
            path = storageClient1.upload_file1(file.getContent(), ext, mata_list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }

    /**
     * fastDFS文件下载
     * @param groupName 组名
     * @param remoteFileName 文件名
     * @param specFileName 真实文件名
     * @return ResponseEntity<byte[]>
     */
    public static ResponseEntity<byte[]> downloadFile(String groupName, String remoteFileName, String specFileName){
        byte[] content = null;
        HttpHeaders headers = new HttpHeaders();
        try {
            content = storageClient1.download_file(groupName, remoteFileName);
            headers.setContentDispositionFormData("attachment",  new String(specFileName.getBytes("UTF-8"),"iso-8859-1"));
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity<byte[]>(content, headers, HttpStatus.CREATED);
    }

    /**
     * 根据fastDFS返回的path得到文件的组名
     * @param path fastDFS返回的path
     * @return
     */
    public static String getGroupFormFilePath(String path){
        return path.split("/")[0];
    }

    /**
     * 根据fastDFS返回的path得到文件名
     * @param path fastDFS返回的path
     * @return
     */
    public static String getFileNameFormFilePath(String path) {
        return path.substring(path.indexOf("/")+1);
    }
}

package net.w2p.DevBase.plugins;

import java.io.Serializable;
import java.util.Arrays;

/**
 * @ClassName FastDFSFile
 * @Description FastDFS上传文件业务对象
 * @author zhangkai
 * @date 2017年7月18日
 */
public class FastDFSFile implements Serializable{

    private static final long serialVersionUID = 2637755431406080379L;
    /**
     * 文件二进制
     */
    private byte[] content;
    /**
     * 文件名称
     */
    private String name;
    /**
     * 文件长度
     */
    private Long size;

    public FastDFSFile(){

    }
    public FastDFSFile(byte[] content, String name, Long size){
        this.content = content;
        this.name = name;
        this.size = size;
    }

    public byte[] getContent() {
        return content;
    }
    public void setContent(byte[] content) {
        this.content = content;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Long getSize() {
        return size;
    }
    public void setSize(Long size) {
        this.size = size;
    }
    public static long getSerialversionuid() {
        return serialVersionUID;
    }
}

测试用文件:

package others;

import main.BaseTest;
import net.w2p.DevBase.plugins.FastDFSFile;
import net.w2p.DevBase.plugins.FastDFSPlugin;
import net.w2p.Shared.common.FileReadUtil;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

import java.io.*;

public class FastDfSTester extends BaseTest {
    private byte[] toByteArray(InputStream in) throws IOException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }

    @Test
    public void test_upload(){
        String encoding = "UTF-8";
        String fileName="/home/2.jpg";
        File file = new File(fileName);
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        try {
            FileInputStream in = new FileInputStream(file);
            byte[] content=toByteArray(in);
            in.close();
            FastDFSFile fastDFSFile = new FastDFSFile(content, file.getName(), filelength);
            String path = FastDFSPlugin.uploadFile(fastDFSFile);
            System.out.println(path);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}

测试结果:
在这里插入图片描述

在这里插入图片描述

done。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值