FastDFS与springBoot集成
参考博客http://blog.csdn.net/xyang81/article/details/52850667
tobato在今年9月份在官方Java客户端的基础上进行了大量重构,且提供了更多丰富的api,主要新增的特性如下:
1 对关键部分代码加入了单元测试,便于理解与服务端的接口交易,提高接口质量
2将以前对byte硬解析风格重构为使用 对象+注解 的形式,尽量增强了代码的可读性
3支持对服务端的连接池管理(commons-pool2)
4支持上传图片时候检查图片格式,并且自动生成缩略图
5和Springboot整合方便
源码下载地址:https://github.com/tobato/FastDFS_Client
整合到Springboot项目流程
1.先创建springboot工程
工程目录如下
添加springboot pom依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
</parent> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> <!-- hot swapping, disable cache for template, enable live reload -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency> <!-- Optional, for bootstrap -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.25.2-RELEASE</version>
</dependency> <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
</dependencies>
<build>
<finalName>fastdfsspringboot</finalName> <plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
将Fdfs配置引入项目
package com.cky.demo; import com.github.tobato.fastdfs.FdfsClientConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import; /**
* Created by chenkaiyang on 2017/11/30.
*/
@Import(FdfsClientConfig.class)
@SpringBootApplication
public class JingtongApplication {
public static void main(String[] args) {
SpringApplication.run(JingtongApplication.class, args);
}
}
application.properties
fdfs.soTimeout=1500
fdfs.connectTimeout=600
fdfs.thumbImage.width=150
fdfs.thumbImage.height=150
fdfs.trackerList[0]=192.168.0.204:22122
在项目中使用
客户端主要包括以下接口:
TrackerClient - TrackerServer接口
GenerateStorageClient - 一般文件存储接口 (StorageServer接口)
FastFileStorageClient - 为方便项目开发集成的简单接口(StorageServer接口)
AppendFileStorageClient - 支持文件续传操作的接口 (StorageServer接口)
基于FastFileStorageClient接口和springmvc提供的MultipartFile接口封装了一个简单的工具类,方便全局管理与调用。如下所示
package com.cky.demo.util; import com.cky.demo.constant.AppConfig;
import com.cky.demo.constant.AppConstants;
import com.github.tobato.fastdfs.domain.StorePath;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.IOException;
import java.nio.charset.Charset; /**
* Created by chenkaiyang on 2017/11/30.
*/
@Component
public class FastDFSClientWrapper { private final Logger logger = LoggerFactory.getLogger(FastDFSClientWrapper.class); @Autowired
private FastFileStorageClient storageClient; @Autowired
private AppConfig appConfig; // 项目参数配置 /**
* 上传文件
* @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 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 = AppConstants.HTTP_PRODOCOL + appConfig.getResHost()
+ ":" + appConfig.getFdfsStoragePort() + "/" + storePath.getFullPath();
return fileUrl;
} /**
* 删除文件
* @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());
}
}
}
除了FastDFSClientWrapper类中用到的api,客户端提供的api还有很多,可根据自身的业务需求,将其它接口也添加到工具类中即可。如下所示:
// 上传文件,并添加文件元数据
StorePath uploadFile(InputStream inputStream, long fileSize, String fileExtName, Set<MateData> metaDataSet);
// 获取文件元数据
Set<MateData> getMetadata(String groupName, String path);
// 上传图片并同时生成一个缩略图
StorePath uploadImageAndCrtThumbImage(InputStream inputStream, long fileSize, String fileExtName,
Set<MateData> metaDataSet);
// 。。。
FastStorage ip和端口配置
package com.cky.demo.constant; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; /**
* Created by chenkaiyang on 2017/11/30.
*/
@Component
public class AppConfig { @Value("${resHost}")
private String resHost;
@Value("${fdfsStoragePort}")
private String fdfsStoragePort; public String getResHost() {
return resHost;
} public void setResHost(String resHost) {
this.resHost = resHost;
} public String getFdfsStoragePort() {
return fdfsStoragePort;
} public void setFdfsStoragePort(String fdfsStoragePort) {
this.fdfsStoragePort = fdfsStoragePort;
}
}
返回图片的连接地址的协议
package com.cky.demo.constant; /**
* Created by chenkaiyang on 2017/11/30.
*/
public class AppConstants { public static final String HTTP_PRODOCOL = "http://";
}
配置controller的页面跳转及上传接口
package com.cky.demo.controller; import com.cky.demo.util.FastDFSClientWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map; /**
* Created by chenkaiyang on 2017/12/1.
*/
@Controller
public class MyController {
@Autowired
private FastDFSClientWrapper dfsClient; @ResponseBody
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public Map<String, String> upload(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
// 省略业务逻辑代码。。。
String imgUrl = dfsClient.uploadFile(file);
Map<String, String> map = new HashMap<>();
map.put("url", imgUrl);
map.put("status", "success");
// 。。。。
return map;
}
@RequestMapping(value = "/topage", method = RequestMethod.GET)
public String toIndex() {
return "01";
}
}
到这里后端的代码就配置完成
下面开始配置前端代码
首先在rescources下面的static目录下的js目录下引入jquery-1.11.3min.js及ajaxfileupload.js
由于高版本的jquery里面会报找不到handleError
因此在ajaxfileupload.js里面开始加入下面的代码
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error ) {
s.error.call( s.context || s, xhr, status, e );
} // Fire the global callback
if ( s.global ) {
(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
}
},
前端html代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/ajaxfileupload.js"></script>
</head>
<body>
<p>
<label>ajax上传</label>
<input type="file" name="file" id="fileToUpload" class="inp_fileToUpload" multiple="multiple"/>
<img src="" width="400px" height="400px" class="img_upload" id="img" />
</p>
<p>
<label>最新修改人员:</label>
<input readonly="readonly" type="text" size="30" />
</p>
</body>
<script type="text/javascript">
$(function() {
$(".inp_fileToUpload").on("change", function() {//现在这个已经适用于多个file表单。
ajaxFileUpload($(this).attr("id"), $(this).parent().children(".img_upload").attr("id"));
})
})
function ajaxFileUpload(file_id, img_id) {
jQuery.ajaxFileUpload({
url : '/upload', //用于文件上传的服务器端请求地址
secureuri : false, //是否需要安全协议,一般设置为false
fileElementId : file_id, //文件上传域的ID
contentType:"application/json;charset=UTF-8",
success : function(data, status)//服务器成功响应处理函数
{
var str = $(data).find("body").text();//获取返回的字符串
var json = $.parseJSON(str);//把字符串转化为json对象
if(json.status){
//alert("上传成功URL为" + json.url);
$("#"+img_id).attr("src", json.url)
}
else{
alert("删除失败");
}
},
error : function(data, status, e)//服务器响应失败处理函数
{
alert(e);
}
})
return false;
}
</script>
</html>
启动springboot
附送项目源码地址:
FastDFS与springBoot集成的更多相关文章
- 实战:docker搭建FastDFS文件系统并集成SpringBoot
实战:docker搭建FastDFS文件系统并集成SpringBoot 前言 15年的时候,那时候云存储还远远没有现在使用的这么广泛,归根结底就是成本和安全问题,记得那时候我待的公司是做建站开发的,前 ...
- 【springBoot】springBoot集成redis的key,value序列化的相关问题
使用的是maven工程 springBoot集成redis默认使用的是注解,在官方文档中只需要2步; 1.在pom文件中引入即可 <dependency> <groupId>o ...
- SpringBoot集成security
本文就SpringBoot集成Security的使用步骤做出解释说明.
- springboot集成Actuator
Actuator监控端点,主要用来监控与管理. 原生端点主要分为三大类:应用配置类.度量指标类.操作控制类. 应用配置类:获取应用程序中加载的配置.环境变量.自动化配置报告等与SpringBoot应用 ...
- SpringBoot集成Shiro并用MongoDB做Session存储
之前项目鉴权一直使用的Shiro,那是在Spring MVC里面使用的比较多,而且都是用XML来配置,用Shiro来做权限控制相对比较简单而且成熟,而且我一直都把Shiro的session放在mong ...
- SpringBoot集成redis的key,value序列化的相关问题
使用的是maven工程 springBoot集成redis默认使用的是注解,在官方文档中只需要2步; 1.在pom文件中引入即可 <dependency> <groupId>o ...
- springboot集成mybatis(二)
上篇文章<springboot集成mybatis(一)>介绍了SpringBoot集成MyBatis注解版.本文还是使用上篇中的案例,咱们换个姿势来一遍^_^ 二.MyBatis配置版(X ...
- springboot集成mybatis(一)
MyBatis简介 MyBatis本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation迁移到了google code,并且改名为MyB ...
- springboot集成redis(mybatis、分布式session)
安装Redis请参考:<CentOS快速安装Redis> 一.springboot集成redis并实现DB与缓存同步 1.添加redis及数据库相关依赖(pom.xml) <depe ...
随机推荐
- list转map
参考https://cloud.tencent.com/developer/article/1033706 import java.lang.reflect.Field; import java.ut ...
- vs2017连接mysql以及问题汇总
https://www.cnblogs.com/eye-like/p/8494355.html https://blog.csdn.net/u012658972/article/details/791 ...
- 78k的text 文件,输出到textbox 竟然用了20几秒的原因
开始查资料以为是io读取的,磁盘速度慢的之类的,后来一想,text 又不是几十万条数据,才那么两千行,咋回事. 原来是循环中不停的修改textbox值导致的. 总结: 比较大的运算,特别是大的循环, ...
- virtaulbox docker虚拟机使用主机代理shandowsocks
1.virtaulbox 配置NatNetwork File->Preference->network->add new nat network 2.virtaulbox 虚拟机配置 ...
- PAT 甲级 1023 Have Fun with Numbers(20)(思路分析)
1023 Have Fun with Numbers(20 分) Notice that the number 123456789 is a 9-digit number consisting exa ...
- 前端面试问题html汇总
1.对WEB标准以及W3C的理解与认识 结构层 html :表示层 css:行为层:js; 标签闭合.标签小写.不乱嵌套.提高搜索机器人搜索机率.使用外链css和js脚本.结构行为表现的分离.文件下 ...
- nodejs buffer 内存泄漏问题
摘自<Node.js 高级编程> var buffer = new Buffer("this is the content of my buffer"); var sm ...
- JianShu_failban2实现动态屏蔽的功能
一,首先是服务安装 #vim /etc/yum.repos.d/Centos-Base.repo 在最新新增 [atrpms] name=Red Hat Enterprise Linux $relea ...
- 一种基于URL数据源的WEB报表插件
完全支持所见所得的报表设计, 支持 PHP ,Java 等所有支持JSON格式的后端. 立即下载测试版本 需要正式版本?请QQ联系:1565498246 或者留言
- PS制作纸质复古野外露营插画分享
经常有人说一些复古风,就觉得蛮难,其实制作过程其实没有想象中复杂,从1850年到2017年,通过这160多年里的平面设计,给我们的作品添加上一些新鲜的灵感和活力,本次教程就来教大家用PS做出耐看的纸质 ...