springboot整合fastdfs分布式文件上传

fastdfs分布式文件上传

1,首先要导入依赖包,但是fastdfs没有直接的maven依赖,要运行fastdfs的src源文件然后打成war包然后放到maven仓库里面,然后再导入依赖

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

2,由于是文件上传是分布式的,所以自己的本地服务器只是一个向导,真正存储文件的是远程的服务器,,所以需要配置远程服务器的host和port,如:


tracker_server=10.9.251.200:22122

3,文件上传工具类的编写,(上传文件和获取文件的地址)

    public FastDfsUtils(String configlocation) throws IOException, MyException {
        //classpath:conf.properties ===>从项目路径找这个conf的文件,然后转换成绝对路径
        if (configlocation.startsWith("classpath")) {
            //从项目路径中查找文件
            configlocation = configlocation.replace("classpath:", getClass().getResource("/").getPath());

//            ClassLoader classLoader = FastDfsUtils.class.getClassLoader();//获取类加载器
//            String path = classLoader.getResource("/").getPath();//获取项目所在的目录位置

        }
        //"classpath:xxx.conf"
        ClientGlobal.init(configlocation);
        trackerClient = new TrackerClient();
        trackerServer = trackerClient.getConnection();

    }

    public String fileUpload(byte[] bs, String ext_name) throws IOException, MyException {
        return fileUpload(bs, ext_name, null);
    }

    public String fileUpload(byte[] bs, String ext_name, NameValuePair[] valuePair) throws IOException, MyException {
        StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);
        String[] resultString = storageClient1.upload_file(bs, ext_name, valuePair);

        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < resultString.length; i++) {
            stringBuffer.append(resultString[i]);
            if (i == 0) {
                stringBuffer.append("/");
            }
        }
        return stringBuffer.toString();
    }

4,工具类编写完成,得手动创建对象,然后注入Controller实现层里面

 @Bean
    public FastDfsUtils fastDfsUtils() throws IOException, MyException {
            FastDfsUtils fastDfsUtils=new FastDfsUtils("classpath:conf.properties");
        return fastDfsUtils;
    }

5,Controller实现层的具体应用

@AutoWried
private FastDfsUtils fastDfsUtils;

String originalFilename = file1.getOriginalFilename();//获取上传的文件的名字
String ext_name = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
String file1address = fastDfsUtils.fileUpload(file1.getBytes(), ext_name);
发布了72 篇原创文章 · 获赞 21 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_39513430/article/details/104143326
今日推荐