前言

对fastdfs文件系统安装后的使用。

fastdfs的安装请参考这篇:docker中搭建fastdfs文件系统(多图)

本文环境:idea + jdk1.8 + maven

本文项目代码:

1、引入依赖

简单说一下这个依赖部分,目前大部分都是采用的如下依赖:

<!-- https://mvnrepository.com/artifact/net.oschina.zcx7878/fastdfs-client-java -->
<dependency>
    <groupid>net.oschina.zcx7878</groupid>
    <artifactid>fastdfs-client-java</artifactid>
    <version>1.27.0.0</version>
</dependency>

本着不重复造轮子,且为了使用方便我们可以去github找一个集成好的依赖:

https://github.com/tobato/fastdfs_client

<dependency>
    <groupid>com.github.tobato</groupid>
    <artifactid>fastdfs-client</artifactid>
    <version>1.27.2</version>
</dependency>

2、将fdfs配置引入项目

只需要创建一个配置类就可以了:

@configuration
@import(fdfsclientconfig.class)
@enablembeanexport(registration = registrationpolicy.ignore_existing)
public class componetimport {
    // 导入依赖组件
}

参考截图:

3、在application.yml当中配置fdfs相关参数

根据自己情况修改相应ip地址及端口号:

server:
  port: 8080

ip: 10.211.55.4 # 根据自己fastdfs服务器修改

fdfs:
  so-timeout: 1501
  connect-timeout: 601
  thumb-image:             #缩略图生成参数
    width: 150
    height: 150
  tracker-list:            #trackerlist参数,支持多个
    - 10.211.55.4:22122
  web-server-url: http://${ip}:8888/

4、client封装工具类

创建fastdfsclient.java包装工具类,方便后面使用:

import com.github.tobato.fastdfs.domain.conn.fdfswebserver;
import com.github.tobato.fastdfs.domain.fdfs.storepath;
import com.github.tobato.fastdfs.domain.proto.storage.downloadbytearray;
import com.github.tobato.fastdfs.exception.fdfsunsupportstorepathexception;
import com.github.tobato.fastdfs.service.fastfilestorageclient;
import org.apache.commons.io.filenameutils;
import org.apache.commons.lang3.stringutils;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.component;
import org.springframework.web.multipart.multipartfile;
import java.io.bytearrayinputstream;
import java.io.file;
import java.io.fileinputstream;
import java.io.ioexception;
import java.nio.charset.charset;

@component
public class fastdfsclient {

    @autowired
    private fastfilestorageclient storageclient;

    @autowired
    private fdfswebserver fdfswebserver;

    /**
     * 上传文件
     * @param file 文件对象
     * @return 文件访问地址
     * @throws ioexception
     */
    public string uploadfile(multipartfile file) throws ioexception {
        storepath storepath = storageclient.uploadfile(file.getinputstream(),file.getsize(), filenameutils.getextension(file.getoriginalfilename()),null);
        return getresaccessurl(storepath);
    }

    /**
     * 上传文件
     * @param file 文件对象
     * @return 文件访问地址
     * @throws ioexception
     */
    public string uploadfile(file file) throws ioexception {
        fileinputstream inputstream = new fileinputstream (file);
        storepath storepath = storageclient.uploadfile(inputstream,file.length(), filenameutils.getextension(file.getname()),null);
        return getresaccessurl(storepath);
    }

    /**
     * 将一段字符串生成一个文件上传
     * @param content 文件内容
     * @param fileextension
     * @return
     */
    public string uploadfile(string content, string fileextension) {
        byte[] buff = content.getbytes(charset.forname("utf-8"));
        bytearrayinputstream stream = new bytearrayinputstream(buff);
        storepath storepath = storageclient.uploadfile(stream,buff.length, fileextension,null);
        return getresaccessurl(storepath);
    }

    /**
     * 封装图片完整url地址
      */
    private string getresaccessurl(storepath storepath) {
        string fileurl = fdfswebserver.getwebserverurl() + storepath.getfullpath();
        return fileurl;
    }

    /**
     * 删除文件
     * @param fileurl 文件访问地址
     * @return
     */
    public void deletefile(string fileurl) {
        if (stringutils.isempty(fileurl)) {
            return;
        }
        try {
            storepath storepath = storepath.parsefromurl(fileurl);
            storageclient.deletefile(storepath.getgroup(), storepath.getpath());
        } catch (fdfsunsupportstorepathexception e) {
            system.out.println(e.getmessage());
            /** todo 只是测试,所以未使用,logger,正式环境请修改打印方式 **/
        }
    }
    /**
     * 下载文件
     *
     * @param fileurl 文件url
     * @return 文件字节
     * @throws ioexception
     */
    public byte[] downloadfile(string fileurl) throws ioexception {
        string group = fileurl.substring(0, fileurl.indexof("/"));
        string path = fileurl.substring(fileurl.indexof("/") + 1);
        downloadbytearray downloadbytearray = new downloadbytearray();
        byte[] bytes = storageclient.downloadfile(group, path, downloadbytearray);
        return bytes;
    }

}

5、创建conttoler测试类

5.1 文件上传测试

@restcontroller
@requestmapping("/file")
public class fileuploadcontroller {

    @autowired
    private fastdfsclient fastdfsclient;

    /**
     * 上传
     * @param file
     * @return
     * @throws ioexception
     */
    @requestmapping("/upload")
    public string uploadfile(multipartfile file) throws ioexception {
        return fastdfsclient.uploadfile(file);
    }

}

执行效果截图:

5.2、下载文件测试

@restcontroller
@requestmapping("/file")
public class fileuploadcontroller {

    @autowired
    private fastdfsclient fastdfsclient;

    /**
     * 下载
     * @param fileurl
     * @param response
     * @throws ioexception
     */
    @requestmapping("/download")
    public void downloadfile(string fileurl, httpservletresponse response) throws ioexception {
        byte[] bytes = fastdfsclient.downloadfile(fileurl);
        /** todo 这里只是为了整合fastdfs,所以写死了文件格式。需要在上传的时候保存文件名。下载的时候使用对应的格式 **/
        response.setheader("content-disposition", "attachment;filename=" + urlencoder.encode("sb.xlsx", "utf-8"));
        response.setcharacterencoding("utf-8");
        servletoutputstream outputstream = null;
        try {
            outputstream = response.getoutputstream();
            outputstream.write(bytes);
        } catch (ioexception e) {
            e.printstacktrace();
        } finally {
            try {
                outputstream.flush();
                outputstream.close();
            } catch (ioexception e) {
                e.printstacktrace();
            }
        }
    }

}

测试下载路径:

http://127.0.0.1:8080/file/download?fileurl=group1/m00/00/00/ctm3bf84r4saepdgaabogl78qcy682.jpg

拼接的参数为:group1/m00/00/00/ctm3bf84r4saepdgaabogl78qcy682.jpg

大家想修改路径的话,需要同步修改 downloadfile() 方法里的分隔方式。

到此这篇关于springboot集成fastdfs依赖实现文件上传的示例的文章就介绍到这了,更多相关springboot fastdfs文件上传内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!