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);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值