FastDFS是通过StorageClient来执行上传操作的

通过看源码我们知道,FastDFS有两个StorageClient工具类。

StorageClient的上传方法upload_file(...)返回的是字符串数组String[],

如[group1,M00/00/00/wKgAb1dBK2iANrayAA1rIuRd3Es112.jpg]

StorageClient1的上传方法upload_file(...)返回的是字符串数组String,

如group1/M00/00/00/wKgAb1dBK2iANrayAA1rIuRd3Es112.jpg,也就是已经帮我们拼接好了

所以使用StorageClient1的上传方法更方便,不用我们自己拼接了。

FastDFSClient
public class FastDFSClient {
    private TrackerClient trackerClient = null;
    private TrackerServer trackerServer = null;
    private StorageServer storageServer = null;
    //使用StorageClient1进行上传
    private StorageClient1 storageClient1 = null;

    public FastDFSClient(String conf) throws Exception {
        //获取classpath路径下配置文件"fdfs_client.conf"的路径
        //conf直接写相对于classpath的位置,不需要写classpath:
        String configPath = this.getClass().getClassLoader().getResource(conf).getFile();
        System.out.println(configPath);
        ClientGlobal.init(configPath);

        trackerClient = new TrackerClient();
        trackerServer = trackerClient.getConnection();
        storageServer = trackerClient.getStoreStorage(trackerServer);
        storageClient1 = new StorageClient1(trackerServer, storageServer);
    }

    public String uploadFile(byte[] file_buff, String file_ext_name) throws Exception {

        String result = storageClient1.upload_file1(file_buff, file_ext_name, null);

        return result;
    }

    public String uploadFile(String local_filename, String file_ext_name) throws Exception {

        String result = storageClient1.upload_file1(local_filename, file_ext_name, null);

        return result;
    }
}

测试

public class FastDFSTest {
    public static void main(String[] args) throws Exception {
        //不要带classpath
        FastDFSClient client = new FastDFSClient("properties/fdfs_client.conf");
        String result = client.uploadFile("C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg", "jpg");
        System.out.println(result);
    }
}

在项目中,图片上传的实现

Service层

@Service
public class PictureServiceImpl implements PictureService {

    //将需要拼接的ip地址写在配置文件中,交给spring管理
    @Value("${IAMGE_SERVER_BASE_UEL}")
    private String IAMGE_SERVER_BASE_UEL;

    @Override
    public PictureResult uploadPic(MultipartFile picFile) {

        PictureResult result = new PictureResult();

        //判断图片是否为空
        if (picFile.isEmpty()) {
            result.setError(1);
            result.setMessage("图片为空");
            return result;
        }
        //上传到图片服务器
        try {
            //获取图片扩展名
            String originalFilename = picFile.getOriginalFilename();
            //取扩展名,不要"."
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            FastDFSClient client = new FastDFSClient("properties/fdfs_client.conf");
            String url = client.uploadFile(picFile.getBytes(), extName);

            //拼接图片服务器的ip的地址(写配置文件中)
            url = IAMGE_SERVER_BASE_UEL + url;

            //把url响应给客户端
            result.setError(0);
            result.setUrl(url);

        } catch (Exception e) {
            e.printStackTrace();
            result.setError(1);
            result.setMessage("图片上传失败");
        }
        return result;
    }
}

表现层

@Controller
public class PictureController {

    @Autowired
    PictureService pictureService;

    @RequestMapping("/pic/upload")
    @ResponseBody
    public PictureResult uploadFile(MultipartFile uploadFile){
        PictureResult result = pictureService.uploadPic(uploadFile);
        return result;
    }
}

经测试发现,chrome可以正常上传,但是firefox不能,说明兼容性有问题

这就要求我们将返回的数据转换成一个字符串文本,浏览器对字符串的兼容性最好、

封装一个工具类

JsonUtils
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtils {

    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将对象转换成json字符串。
     */
    public static String objectToJson(Object data) {
        try {
            String string = MAPPER.writeValueAsString(data);
            return string;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将json结果集转化为对象
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将json数据转换成pojo对象list
     */
    public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            List<T> list = MAPPER.readValue(jsonData, javaType);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

}

修改后的controller

@Controller
public class PictureController {

    @Autowired
    PictureService pictureService;

    @RequestMapping("/pic/upload")
    @ResponseBody
    public String uploadFile(MultipartFile uploadFile){
        PictureResult result = pictureService.uploadPic(uploadFile);
        //需要把java对象转换成json数据
        String json = JsonUtils.objectToJson(result);
        return json;
    }
}

fastdfs-client-java工具类封装的更多相关文章

  1. Redis操作Set工具类封装,Java Redis Set命令封装

    Redis操作Set工具类封装,Java Redis Set命令封装 >>>>>>>>>>>>>>>>& ...

  2. Redis操作List工具类封装,Java Redis List命令封装

    Redis操作List工具类封装,Java Redis List命令封装 >>>>>>>>>>>>>>>> ...

  3. 排名前 16 的 Java 工具类

    在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码. 一. ...

  4. 排名前16的Java工具类

    原文:https://www.jianshu.com/p/9e937d178203 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法 ...

  5. 干货:排名前16的Java工具类

    在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码. 一. ...

  6. (转载) 百度地图工具类封装(包括定位,附近、城市、范围poi检索,反地理编码)

    目录视图 摘要视图 订阅 赠书 | 异步2周年,技术图书免费选      程序员8月书讯      项目管理+代码托管+文档协作,开发更流畅 百度地图工具类封装(包括定位,附近.城市.范围poi检索, ...

  7. 常用高效 Java 工具类总结

    一.前言 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码 ...

  8. 几种高效的Java工具类推荐

    本文将介绍了十二种常用的.高效的Java工具类 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类. 在开发中,使用这些工具类,不仅可以提高编码效率,还 ...

  9. 16 个超级实用的 Java 工具类

    阅读本文大概需要 4 分钟. 出处:alterem juejin.im/post/5d4a25b351882505c105cc6e 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用 ...

  10. 超级实用的 Java 工具类

    超级实用的 Java 工具类 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取 ...

随机推荐

  1. IOS常用加密Encryption

    NSString+Encryption.h // // NSString+Encryption.h // haochang // // Created by Administrator on 14-4 ...

  2. Zabbix全方位告警接入-电话/微信/短信都支持

    百度告警平台地址: http://gaojing.baidu.com 联系我们: 邮箱:gaojing@baidu.com 电话:13924600771 QQ群:183806029 对于使用zabbi ...

  3. 关于Google+以及Facebook第三方登录实现的一点总结

    简述 最近项目中有关于第三方登陆的需求,第三方Facebook以及Google +登录. 正好这几天把这个需求做得差不多了,收个尾,作为一个这方面之前基本从未涉及的小白,总结下开发流程以及过程中遇到的 ...

  4. 重装系统必做之——更换Windows系统的默认临时文件的存储目录

    作为一名计算机爱好者,重装电脑是家常便饭,但是重装电脑的目的无非就是: 1.操作系统更新换代: 2.系统速度太慢: 或者更多.... 我们大多数目的都是上述中第2点,有时候是否仅仅重装系统而忽略了一些 ...

  5. 设计模式之装饰模式(Decorator)

    装饰模式原理:给对象增加特性,这种特性是一种累加的效果 代码如下 #include <iostream> #include <string> #include <list ...

  6. poj 1463 Strategic game

    题目链接:http://poj.org/problem?id=1463 题意:给出一个无向图,每个节点只有一个父亲节点,可以有多个孩子节点,在一个节点上如果有一位战士守着,那么他可以守住和此节点相连的 ...

  7. Maven安装和配置,eclipse创建Maven项目

    提示:使用Maven需要先安装jdk. 下载安装Maven 一.下载最新版的Maven,下载地址:http://maven.apache.org/download.cgi 二.将Maven下载到E:\ ...

  8. HDOJ1050

    Moving Tables Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Tot ...

  9. ISIN编码

    国际证券识别编码(ISIN编码)是由国际标准化组织(ISO)制定的证券编码标准,并在<证券及相关金融工具-国际证券识别编码体系>(ISO6166)中正式发布.ISO6166主要规定了ISI ...

  10. 通过 Mesos、Docker 和 Go,使用 300 行代码创建一个分布式系统

    [摘要]虽然 Docker 和 Mesos 已成为不折不扣的 Buzzwords ,但是对于大部分人来说它们仍然是陌生的,下面我们就一起领略 Mesos .Docker 和 Go 配合带来的强大破坏力 ...