原文地址: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. linux physical and virtual addressing modes

    example 1: 特理地址和虚拟地址一致 Physical addressing mode requires no page tables and the CPU does not attempt ...

  2. ShellExecute函数的问题

    情境:自己写了一个loading画面,定时器到时间后调用shellexecute函数调用真正的程序. 问题:调用时出错,说找不到dll资源,但是用鼠标双击确可以打开. 经过分析之后,应该是路径的问题, ...

  3. Visual Studio build tools 安装出错的一种解决办法

    一般是安装包丢失或损坏,那么我么可以用离线下载的方式来先行下载. 用 -h 看下帮助 主要是Layout参数. 下载完,到下载目录安装吧.

  4. 清除 eclipse svn 账号密码

    进入目录 C:\Documents and Settings\administrator\Application Data\Subversion\auth 删除目录下所有文件,然后重新刷新svn地址就 ...

  5. PostgreSQL11.2 configure卡住 checking for DocBook XML V4.2

    在PG11.2的数据库编译过程中,卡在了“checking for DocBook XML V4.2”,不动,需要安装docbook才可以. 需要安装: yum install docbook-dtd ...

  6. 使用jenkins进行项目的自动构建部署

    jenkins 简介 Jenkins是基于Java开发的一种持续集成工具,用于监控持续重复的工作,功能包括:持续的软件版本发布/测试项目和监控外部调用执行的工作. 官网地址地址: https://je ...

  7. layer弹出相册层

    如果想要制作一个简单的相册,可以采用这个插件的方法.如果你的图片是从后台传过来的json格式里,可以通过ajax加载让图片显示在页面上,然后在使用layer插件,做出点击以后就可以查看大图的效果. 一 ...

  8. K - Strange Country II 暴力dfs判断有向图是否连通//lxm

    You want to visit a strange country. There are n cities in the country. Cities are numbered from 1 t ...

  9. ubuntu16.04-caffe安装过程详解-草稿

    前言 目前主要模块都是基于深度学习展开的,虽然知道一些深度学习的基础知识,只是皮毛,还没有使用深度学习框架练手甚至深入,故开始着手深度学习的实操和深入学习. 操作步骤 参考 1.Ubuntu16.04 ...

  10. Wireless Network 并查集

    An earthquake takes place in Southeast Asia. The ACM (Asia Cooperated Medical team) have set up a wi ...