(转)Spring Boot(十八):使用 Spring Boot 集成 FastDFS
http://www.ityouknow.com/springboot/2018/01/16/spring-boot-fastdfs.html
上篇文章介绍了如何使用 Spring Boot 上传文件,这篇文章我们介绍如何使用 Spring Boot 将文件上传到分布式文件系统 FastDFS 中。
这个项目会在上一个项目的基础上进行构建。
1、pom 包配置
<dependency>
<groupId>org.csource</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27-SNAPSHOT</version>
</dependency>
加入了fastdfs-client-java
包,用来调用 FastDFS 相关的 API。
2、配置文件
resources 目录下添加fdfs_client.conf
文件
connect_timeout = 60
network_timeout = 60
charset = UTF-8
http.tracker_http_port = 8080
http.anti_steal_token = no
http.secret_key = 123456
tracker_server = 192.168.53.85:22122
tracker_server = 192.168.53.86:22122
配置文件设置了连接的超时时间,编码格式以及 tracker_server 地址等信息
详细内容参考:fastdfs-client-java
3、封装 FastDFS 上传工具类
封装FastDFSFile,文件基础信息包括文件名、内容、文件类型、作者等。
public class FastDFSFile {
private String name;
private byte[] content;
private String ext;
private String md5;
private String author;
//省略getter、setter
}
封装 FastDFSClient 类,包含常用的上传、下载、删除等方法。
首先在类加载的时候读取相应的配置信息,并进行初始化。
static {
try {
String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();;
ClientGlobal.init(filePath);
trackerClient = new TrackerClient();
trackerServer = trackerClient.getConnection();
storageServer = trackerClient.getStoreStorage(trackerServer);
} catch (Exception e) {
logger.error("FastDFS Client Init Fail!",e);
}
}
文件上传
public static String[] upload(FastDFSFile file) {
logger.info("File Name: " + file.getName() + "File Length:" + file.getContent().length);
NameValuePair[] meta_list = new NameValuePair[1];
meta_list[0] = new NameValuePair("author", file.getAuthor());
long startTime = System.currentTimeMillis();
String[] uploadResults = null;
try {
storageClient = new StorageClient(trackerServer, storageServer);
uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
} catch (IOException e) {
logger.error("IO Exception when uploadind the file:" + file.getName(), e);
} catch (Exception e) {
logger.error("Non IO Exception when uploadind the file:" + file.getName(), e);
}
logger.info("upload_file time used:" + (System.currentTimeMillis() - startTime) + " ms");
if (uploadResults == null) {
logger.error("upload file fail, error code:" + storageClient.getErrorCode());
}
String groupName = uploadResults[0];
String remoteFileName = uploadResults[1];
logger.info("upload file successfully!!!" + "group_name:" + groupName + ", remoteFileName:" + " " + remoteFileName);
return uploadResults;
}
使用 FastDFS 提供的客户端 storageClient 来进行文件上传,最后将上传结果返回。
根据 groupName 和文件名获取文件信息。
public static FileInfo getFile(String groupName, String remoteFileName) {
try {
storageClient = new StorageClient(trackerServer, storageServer);
return storageClient.get_file_info(groupName, remoteFileName);
} catch (IOException e) {
logger.error("IO Exception: Get File from Fast DFS failed", e);
} catch (Exception e) {
logger.error("Non IO Exception: Get File from Fast DFS failed", e);
}
return null;
}
下载文件
public static InputStream downFile(String groupName, String remoteFileName) {
try {
storageClient = new StorageClient(trackerServer, storageServer);
byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
InputStream ins = new ByteArrayInputStream(fileByte);
return ins;
} catch (IOException e) {
logger.error("IO Exception: Get File from Fast DFS failed", e);
} catch (Exception e) {
logger.error("Non IO Exception: Get File from Fast DFS failed", e);
}
return null;
}
删除文件
public static void deleteFile(String groupName, String remoteFileName)
throws Exception {
storageClient = new StorageClient(trackerServer, storageServer);
int i = storageClient.delete_file(groupName, remoteFileName);
logger.info("delete file successfully!!!" + i);
}
使用 FastDFS 时,直接调用 FastDFSClient 对应的方法即可。
4、编写上传控制类
从 MultipartFile 中读取文件信息,然后使用 FastDFSClient 将文件上传到 FastDFS 集群中。
public String saveFile(MultipartFile multipartFile) throws IOException {
String[] fileAbsolutePath={};
String fileName=multipartFile.getOriginalFilename();
String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
byte[] file_buff = null;
InputStream inputStream=multipartFile.getInputStream();
if(inputStream!=null){
int len1 = inputStream.available();
file_buff = new byte[len1];
inputStream.read(file_buff);
}
inputStream.close();
FastDFSFile file = new FastDFSFile(fileName, file_buff, ext);
try {
fileAbsolutePath = FastDFSClient.upload(file); //upload to fastdfs
} catch (Exception e) {
logger.error("upload file Exception!",e);
}
if (fileAbsolutePath==null) {
logger.error("upload file failed,please upload again!");
}
String path=FastDFSClient.getTrackerUrl()+fileAbsolutePath[0]+ "/"+fileAbsolutePath[1];
return path;
}
请求控制,调用上面方法saveFile()
。
@PostMapping("/upload") //new annotation since 4.3
public String singleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:uploadStatus";
}
try {
// Get the file and save it somewhere
String path=saveFile(file);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded '" + file.getOriginalFilename() + "'");
redirectAttributes.addFlashAttribute("path",
"file path url '" + path + "'");
} catch (Exception e) {
logger.error("upload file failed",e);
}
return "redirect:/uploadStatus";
}
上传成功之后,将文件的路径展示到页面,效果图如下:
在浏览器中访问此Url,可以看到成功通过FastDFS展示:
这样使用 Spring Boot 集成 FastDFS 的案例就完成了。文章内容已经升级到 Spring Boot 2.x
(转)Spring Boot(十八):使用 Spring Boot 集成 FastDFS的更多相关文章
- Spring Boot(十八):使用Spring Boot集成FastDFS
Spring Boot(十八):使用Spring Boot集成FastDFS 环境:Spring Boot最新版本1.5.9.jdk使用1.8.tomcat8.0 功能:使用Spring Boot将文 ...
- Spring Boot 2 (八):Spring Boot 集成 Memcached
Spring Boot 2 (八):Spring Boot 集成 Memcached 一.Memcached 介绍 Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数 ...
- Spring Boot(十五):spring boot+jpa+thymeleaf增删改查示例
Spring Boot(十五):spring boot+jpa+thymeleaf增删改查示例 一.快速上手 1,配置文件 (1)pom包配置 pom包里面添加jpa和thymeleaf的相关包引用 ...
- Spring Boot(十四):spring boot整合shiro-登录认证和权限管理
Spring Boot(十四):spring boot整合shiro-登录认证和权限管理 使用Spring Boot集成Apache Shiro.安全应该是互联网公司的一道生命线,几乎任何的公司都会涉 ...
- Spring Boot(十二):spring boot如何测试打包部署
Spring Boot(十二):spring boot如何测试打包部署 一.开发阶段 1,单元测试 在开发阶段的时候最重要的是单元测试了,springboot对单元测试的支持已经很完善了. (1)在p ...
- Spring入门(十四):Spring MVC控制器的2种测试方法
作为一名研发人员,不管你愿不愿意对自己的代码进行测试,都得承认测试对于研发质量保证的重要性,这也就是为什么每个公司的技术部都需要质量控制部的原因,因为越早的发现代码的bug,成本越低,比如说,Dev环 ...
- Spring Boot(十八):使用 Spring Boot 集成 FastDFS
上篇文章介绍了如何使用 Spring Boot 上传文件,这篇文章我们介绍如何使用 Spring Boot 将文件上传到分布式文件系统 FastDFS 中. 这个项目会在上一个项目的基础上进行构建. ...
- spring boot(十八)集成FastDFS文件上传下载
上篇文章介绍了如何使用Spring Boot上传文件,这篇文章我们介绍如何使用Spring Boot将文件上传到分布式文件系统FastDFS中. 这个项目会在上一个项目的基础上进行构建. 1.pom包 ...
- (转)Spring Boot 2 (八):Spring Boot 集成 Memcached
http://www.ityouknow.com/springboot/2018/09/01/spring-boot-memcached.html Memcached 介绍 Memcached 是一个 ...
随机推荐
- [日常] HTTP协议状态码
100-199 信息性状态码 100 continue 请继续 101 switching protocols 切换协议,返回upgraded头 200-299 成功状态码 200 ok 201 cr ...
- spring2.0:The server time zone value 'Ãùú±êüñ¼ä' is unrecognized or represents more than one time zone. You must configure either th
提示系统时区出现错误,可以在mysql中执行命令: set global time_zone='+8:00' 或者在数据库驱动的url后加上serverTimezone=UTC参数 jdbc:mysq ...
- Java马士兵高并发编程视频学习笔记(一)
1.同一个资源,同步和非同步的方法可以同时调用 package com.dingyu; public class Y { public synchronized void m1() { System. ...
- 一些你可能不熟悉的JS知识点总结
js代码暂时性死区 只要块级作用域存在let命令,它所声明的变量就“绑定”这个区域,不再受外部的影响.这么说可能有些抽象,举个例子: ? 1 2 3 4 5 var temp = 123; if(tr ...
- 洛谷P4302 [SCOI2003]字符串折叠(区间dp)
题意 题目链接 Sol 裸的区间dp. 转移的时候枚举一下断点.然后判断一下区间内的字符串是否循环即可 `cpp #include<bits/stdc++.h> #define Pair ...
- AI产品经理成长路
AI产品经理成长路 https://www.jianshu.com/p/4b98314ad3c0 以下都是自己平时知识的一些总结,只是一些个人的愚见,下面出现的公司.书籍.视频.网站都是自己看过体验过 ...
- 在“非软件企业”开发软件的困局 ZT
软件产品广泛服务于各行业,其开发具有高科技.高投入.高产出.高风险的特点.在项目开发和软件应用中,只有将人员能力的发挥与科学技术的使用应用市场的认识进行最佳的融合,才能发挥软件的效益.普通企业虽涉足软 ...
- Android为TV端助力 计算每个目录剩余空间丶总空间以及SD卡剩余空间
ublic class MemorySpaceCheck { /** * 计算剩余空间 * @param path * @return */ public static String getAvail ...
- OkHttp的封装和使用详解
Github地址 compile 'cn.yuan.yu:library:1.0.2' 第一步:初始化我们的工具类 public class MyApplication extends Applica ...
- <自动化测试方案_1>第一章、为什么要做自动化测试?(Why)
第一章.为什么要做自动化测试?(Why) 测试的产品分为:桌面程序(C/S).web应用(B/S) 我们的产品是B/S (一)迭代中省去人力测试非新增功能: 在项目中由于测试时间的限制,测试中只能实现 ...