FastDFS图片上传工具类

北城余情 提交于 2020-01-17 01:15:27
public class UploadUtil {

    public static String uploadImage(MultipartFile multipartFile){

        String imgUrl = Constant.trackerServerIP; //fastdfs服务器ip自行设置

        //上传图片服务器
        //配置fdfs的全局链接地址
        String tracker = PmsUploadUtil.class.getResource("/tracker.conf").getPath();//获得配置文件的路径

        try {
            ClientGlobal.init(tracker);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }

        TrackerClient trackerClient = new TrackerClient();
        //获得trackerServer的实例
        TrackerServer trackerServer = null;
        try {
            trackerServer = trackerClient.getConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //通过tracker获得Storage链接客户端
        StorageClient storageClient = new StorageClient(trackerServer, null);

        byte[] bytes =null;
        try {
            bytes = multipartFile.getBytes(); //获得上传的二进制对象
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获取文件后缀名
        String originalFilename = multipartFile.getOriginalFilename();
        String extName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);

        //获取返回的文件信息数组
        String [] uploadInfos = null;
        try {
            uploadInfos = storageClient.upload_file(bytes,extName,null);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }

        //获取图片服务器路径
        for (String uploadInfo : uploadInfos) {
            imgUrl += "/"+uploadInfo;
        }

        return imgUrl;
    }


}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!