原文地址:Spring Boot 整合 FastDFS 客户端

博客地址:http://www.extlight.com

一、前言

前两篇介绍整体上介绍了通过 Nginx 和 FastDFS 的整合来实现文件服务器。但是,在实际开发中对图片或文件的操作都是通过应用程序来完成的,因此,本篇将介绍 Spring Boot 整合 FastDFS 客户端来实现对图片/文件服务器的访问。

如果有不了解 FastDFS 的读者可以先浏览《FastDFS 环境搭建》《Nginx 整合 FastDFS 实现文件服务器》 来普及内容,或是另行查阅网上相关资料。

二、整合编码

2.1 添加依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<scope>true</scope>
</dependency> <dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.26.3</version>
</dependency> <dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

上边的 fastdfs-client 是并非 FastDFS Client 原作者编写的整合包,具体详情可以访问 https://github.com/tobato/FastDFS_Client

2.2 application.properties

server.port=8080

# fastDFS 配置
fdfs.so-timeout=1501
fdfs.connect-timeout=601
fdfs.thumb-image.width=150
fdfs.thumb-image.height=150
fdfs.web-server-url=192.168.10.110/
fdfs.tracker-list[0]=192.168.10.110:22122

2.3 后端代码

  • 加载 FastDFS 配置类:
@Configuration
@Import(FdfsClientConfig.class)
// 解决jmx重复注册bean的问题
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class ComponetImport {
// 导入依赖组件
}
  • FastDFS 工具类:
@Component
public class FastDFSClient { private final Logger logger = LoggerFactory.getLogger(FastDFSClient.class); @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 文件url
* @return
*/
public byte[] download(String fileUrl) {
String group = fileUrl.substring(0, fileUrl.indexOf("/"));
String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
byte[] bytes = storageClient.downloadFile(group, path, new DownloadByteArray());
return bytes;
} /**
* 删除文件
* @param fileUrl 文件访问地址
* @return
*/
public void deleteFile(String fileUrl) {
if (StringUtils.isEmpty(fileUrl)) {
return;
}
try {
StorePath storePath = StorePath.praseFromUrl(fileUrl);
storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
} catch (FdfsUnsupportStorePathException e) {
logger.warn(e.getMessage());
}
} }
  • controller 类:
@RestController
@RequestMapping("/fdfs")
public class FastDFSController { @Autowired
private FastDFSClient fdfsClient; /**
* 文件上传
* @param file
* @return
* @throws Exception
*/
@RequestMapping("/upload")
public Map<String,Object> upload(MultipartFile file) throws Exception{ String url = fdfsClient.uploadFile(file); Map<String,Object> result = new HashMap<>();
result.put("code", 200);
result.put("msg", "上传成功");
result.put("url", url); return result;
} /**
* 文件下载
* @param fileUrl url 开头从组名开始
* @param response
* @throws Exception
*/
@RequestMapping("/download")
public void download(String fileUrl, HttpServletResponse response) throws Exception{ byte[] data = fdfsClient.download(fileUrl); response.setCharacterEncoding("UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("test.jpg", "UTF-8")); // 写出
ServletOutputStream outputStream = response.getOutputStream();
IOUtils.write(data, outputStream);
}
}

2.4 前端页面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.css}">
<style>
form {
margin-top: 30px;
}
</style>
</head>
<body>
<div class="container"> <div class="row">
<div class="col-md-4 col-sm-4"></div>
<div class="col-md-4 col-sm-4">
<h2> FastDFS 文件上传</h2>
<form th:action="@{/fdfs/upload}" method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="file" name="file" id="exampleInputFile">
</div>
<button type="submit" class="btn btn-default">上传</button>
</form>
</div>
<div class="col-md-4 col-sm-4"></div>
</div>
</div>
</body>
</html>

三、测试

本篇只测试文件上传和访问的效果,演示图如下:

整合成功~~

Spring Boot 整合 FastDFS 客户端的更多相关文章

  1. Spring Kafka整合Spring Boot创建生产者客户端案例

    每天学习一点点 编程PDF电子书.视频教程免费下载:http://www.shitanlife.com/code 创建一个kafka-producer-master的maven工程.整个项目结构如下: ...

  2. Spring Boot 整合 Elasticsearch,实现 function score query 权重分查询

    摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 预见未来最好的方式就是亲手创造未来 – <史蒂夫·乔布斯传> 』 运行环境: ...

  3. Spring Kafka和Spring Boot整合实现消息发送与消费简单案例

    本文主要分享下Spring Boot和Spring Kafka如何配置整合,实现发送和接收来自Spring Kafka的消息. 先前我已经分享了Kafka的基本介绍与集群环境搭建方法.关于Kafka的 ...

  4. Spring Boot整合Elasticsearch

    Spring Boot整合Elasticsearch   Elasticsearch是一个全文搜索引擎,专门用于处理大型数据集.根据描述,自然而然使用它来存储和搜索应用程序日志.与Logstash和K ...

  5. (转)Spring Boot(十八):使用 Spring Boot 集成 FastDFS

    http://www.ityouknow.com/springboot/2018/01/16/spring-boot-fastdfs.html 上篇文章介绍了如何使用 Spring Boot 上传文件 ...

  6. Spring Boot初识(4)- Spring Boot整合JWT

    一.本文介绍 上篇文章讲到Spring Boot整合Swagger的时候其实我就在思考关于接口安全的问题了,在这篇文章了我整合了JWT用来保证接口的安全性.我会先简单介绍一下JWT然后在上篇文章的基础 ...

  7. Spring Boot(十八):使用 Spring Boot 集成 FastDFS

    上篇文章介绍了如何使用 Spring Boot 上传文件,这篇文章我们介绍如何使用 Spring Boot 将文件上传到分布式文件系统 FastDFS 中. 这个项目会在上一个项目的基础上进行构建. ...

  8. Spring Boot(十八):使用Spring Boot集成FastDFS

    Spring Boot(十八):使用Spring Boot集成FastDFS 环境:Spring Boot最新版本1.5.9.jdk使用1.8.tomcat8.0 功能:使用Spring Boot将文 ...

  9. spring boot整合Swagger2

    Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化RESTful风格的 Web 服务.总体目标是使客户端和文件系统作为服务器以同样的速度来更新.文件的方法,参数和模型紧密集成到服务器 ...

随机推荐

  1. ORACLE常见方法使用(转)

    1.DBMS_LOB包的使用 2.如何释放DBMS_LOB.CREATETEMPORARY的空间 3.oracle数组

  2. kill word out e ef en em

        1● e 2● ef 出,出来   3● en 4● em 使~进入状态,包围,进入~之中  

  3. 蓝桥杯—ALGO-122 未名湖畔的烦恼(枚举)

    问题描述 每年冬天,北大未名湖上都是滑冰的好地方.北大体育组准备了许多冰鞋,可是人太多了, 每天下午收工后,常常一双冰鞋都不剩. 每天早上,租鞋窗口都会排起长龙,假设有还鞋的m个,有需要租鞋的n个. ...

  4. Webserivce简单安全验证

    最近新接了一个需要调用第三方WebService的项目,看到这个第三方WebService被调用的时候,需要授权用户名和密码,于是自己也想对WebService的安全授权这个方面进行了一下研究,以前调 ...

  5. (zz)设置单元格的宽度和高度

    (zz)设置单元格的宽度和高度 博客分类: POI生成Excel   在Excel中,单元格的宽度其实就是列的宽度,因为Excel假设这一列的单元格的宽度肯定一致.所以要设置单元格的宽度,我们就得从列 ...

  6. 一个在windows电脑上控制比较全的文件夹的设置方式

    一个在windows电脑上控制比较全的文件夹的设置方式: 1.在桌面上创建一个新建文件夹 2.将新建文件夹重命名为  万能控制模式.{ED7BA470-8E54-465E-825C-99712043E ...

  7. 再谈Contacts中姓氏多音字排序错误问题

    说到中国人的名字,那就不得不考虑多音字的问题,比如'单',在作为姓氏时应该读作'shan'而不是'dan'.但是在Contacts程序中却使用的是'D'来作为bucket label!这是为什么?如何 ...

  8. xxx/labelKeypoint/utils/qt.py:81: RuntimeWarning: invalid value encountered in double_scalars

    原代码: return np.linalg.norm(np.cross(p2 - p1, p1 - p3)) / np.linalg.norm(p2 - p1) 出现报错: xxx/labelKeyp ...

  9. linux rinetd、socat端口转发部署(很实用的网络工具)

    端口转发映射的程序叫rinetd,下载地址,直接manke编译安装即可. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 [root@PortForward02 src] ...

  10. ES6.0 Generator 三种用法

    // Generator start ------- thunk 用法 const Thunk = function(fn) { return function (...args) { return ...