只支持在spring-boot 2.0以及以上版本中使用

1.pom.xml 里引入FASTDFS的依赖,toobato与fastdfs作者一起,将fastdfs的功能进行了重构与简化

<!-- 高性能分布式文件服务器 -->
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.26.2</version>
</dependency>
2.引入spring-test的依赖,里面有将可以将文件对象转换为MutipartFile的方法
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>

3.创建一个FastdfsImporter 类(随便起名),在类里面1定义如下配置,就可以将作者的fastDFS中的bean进行引入

@Configuration
@Import(FdfsClientConfig.class)//@Import可以导入一个带有@configuration注解的类;
// 解决jmx重复注册bean的问题
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FastdfsImporter {
// 导入依赖组件
}

4.spring boot 配置文件中引入如下

fdfs.soTimeout=1501
fdfs.connectTimeout=601
#image size ,在方法中可以使用生成自定义的图片大小
fdfs.thumbImage.width=80
fdfs.thumbImage.height=80
# fastdfs address and port
fdfs.trackerList[0]=192.168.241.129:22122

5.接下来,提供给两个类,直接复制到自己的程序中,进行调用即可

----------------FastDFSClient----------------------直接用此类方法就可以将文件传入fastdfs图片服务器中

package com.project.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.Charset; 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 com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient; @Component
public class FastDFSClient { @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 storePath.getPath();
} public String uploadFile2(MultipartFile file) throws IOException {
StorePath storePath = storageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(),
FilenameUtils.getExtension(file.getOriginalFilename()), null); return storePath.getPath();
} public String uploadQRCode(MultipartFile file) throws IOException {
StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
"png", null); return storePath.getPath();
} public String uploadFace(MultipartFile file) throws IOException {
StorePath storePath = storageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(),
"png", null); return storePath.getPath();
} public String uploadBase64(MultipartFile file) throws IOException {
StorePath storePath = storageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(),
"png", null); return storePath.getPath();
} /**
* 将一段字符串生成一个文件上传
*
* @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 storePath.getPath();
} // 封装图片完整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) {
e.getMessage();
}
}
}

------------------ FileUtils----------提供了对文件操作,可以将file 对象转换为MutipartFile,base64字符串转换为文件(根据需要引入此类)

package com.project.util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL; import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile; @Service
public class FileUtils {
/**
* 根据url拿取file
*
* @param url
* @param suffix
* 文件后缀名
*/
public static File createFileByUrl(String url, String suffix) {
byte[] byteFile = getImageFromNetByUrl(url);
if (byteFile != null) {
File file = getFileFromBytes(byteFile, suffix);
return file;
} else {
return null;
}
} /**
* 根据地址获得数据的字节流
*
* @param strUrl
* 网络连接地址
* @return
*/
private static byte[] getImageFromNetByUrl(String strUrl) {
try {
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();// 通过输入流获取图片数据
byte[] btImg = readInputStream(inStream);// 得到图片的二进制数据
return btImg;
} catch (Exception e) {
e.printStackTrace();
}
return null;
} /**
* 从输入流中获取数据
*
* @param inStream
* 输入流
* @return
* @throws Exception
*/
private static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
} // 创建临时文件
private static File getFileFromBytes(byte[] b, String suffix) {
BufferedOutputStream stream = null;
File file = null;
try {
file = File.createTempFile("pattern", "." + suffix);
System.out.println("临时文件位置:" + file.getCanonicalPath());
FileOutputStream fstream = new FileOutputStream(file);
stream = new BufferedOutputStream(fstream);
stream.write(b);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return file;
} public static MultipartFile createImg(String url) {
try {
// File转换成MutipartFile
File file = FileUtils.createFileByUrl(url, "jpg");
FileInputStream inputStream = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile(file.getName(), inputStream);
return multipartFile;
} catch (IOException e) {
e.printStackTrace();
return null;
}
} /////////使用spring-test/////////////////
public static MultipartFile fileToMultipart(String filePath) {
try {
// File转换成MutipartFile
File file = new File(filePath);
FileInputStream inputStream = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile(file.getName(), "png", "image/png", inputStream);
return multipartFile;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
} public static void main(String[] args) {
// WebFileUtils.createFileByUrl("http://122.152.205.72:88/group1/M00/00/01/CpoxxFr7oIaAZ0rOAAC0d3GKDio580.png",
// "png");
// WebFileUtils.createImg("http://122.152.205.72:88/group1/M00/00/01/CpoxxFr7oIaAZ0rOAAC0d3GKDio580.png");
} public static boolean base64ToFile(String filePath, String base64Data) throws Exception {
String dataPrix = "";
String data = ""; if(base64Data == null || "".equals(base64Data)){
return false;
}else{
String [] d = base64Data.split("base64,");
if(d != null && d.length == 2){
dataPrix = d[0];
data = d[1];
}else{
return false;
}
} // 因为BASE64Decoder的jar问题,此处使用spring框架提供的工具包
byte[] bs = Base64Utils.decodeFromString(data);
// 使用apache提供的工具类操作流
org.apache.commons.io.FileUtils.writeByteArrayToFile(new File(filePath), bs); return true;
}
}

  

spring boot 2.0 与FASTDFS进行整合的更多相关文章

  1. Spring Boot 2.0 教程 | 快速集成整合消息中间件 Kafka

    欢迎关注个人微信公众号: 小哈学Java, 每日推送 Java 领域干货文章,关注即免费无套路附送 100G 海量学习.面试资源哟!! 个人网站: https://www.exception.site ...

  2. spring boot 2.0 整合 elasticsearch6.5.3,spring boot 2.0 整合 elasticsearch NoNodeAvailableException

    原文地址:spring boot 2.0 整合 elasticsearch NoNodeAvailableException 原文说的有点问题,下面贴出我的配置: 原码云项目地址:https://gi ...

  3. Spring Boot 2.0 整合 FreeMarker 模板引擎

    本篇博文将和大家一起使用Spring Boot 2.0 和FreeMarker 模板引擎整合实战. 1. 创建新的项目 2. 填写项目配置信息 3. 勾选web 模块 4. 勾选freemarker模 ...

  4. Spring Boot 2.0 整合携程Apollo配置中心

    原文:https://www.jianshu.com/p/23d695af7e80 Apollo(阿波罗)是携程框架部门研发的分布式配置中心,能够集中化管理应用不同环境.不同集群的配置,配置修改后能够 ...

  5. Spring Boot 2.0 整合Thymeleaf 模板引擎

    本节将和大家一起实战Spring Boot 2.0 和thymeleaf 模板引擎 1. 创建项目 2. 使用Spring Initlizr 快速创建Spring Boot 应用程序 3. 填写项目配 ...

  6. springboot2.0(一):【重磅】Spring Boot 2.0权威发布

    就在昨天Spring Boot2.0.0.RELEASE正式发布,今天早上在发布Spring Boot2.0的时候还出现一个小插曲,将Spring Boot2.0同步到Maven仓库的时候出现了错误, ...

  7. 业余草分享 Spring Boot 2.0 正式发布的新特性

    就在昨天Spring Boot2.0.0.RELEASE正式发布,今天早上在发布Spring Boot2.0的时候还出现一个小插曲,将Spring Boot2.0同步到Maven仓库的时候出现了错误, ...

  8. Spring Boot 2.0 的快速入门(图文教程)

    摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠BYSocket 」欢迎关注和转载,保留摘要,谢谢! Spring Boot 2.0 的快速入门(图文教程) 大家都 ...

  9. (转)Spring Boot 2(一):【重磅】Spring Boot 2.0权威发布

    http://www.ityouknow.com/springboot/2018/03/01/spring-boot-2.0.html 就在今天Spring Boot2.0.0.RELEASE正式发布 ...

随机推荐

  1. Redis进阶实践之五Redis的高级特性(转载 5)

    Redis进阶实践之五Redis的高级特性 一.引言 上一篇文章写了Redis的特征,使用场景,同时也介绍了Redis的基本数据类型,redis的数据类型是操作redis的基础,这个必须好好的掌握.今 ...

  2. 【364】SVM 通过 sklearn 可视化实现

    先看下效果图: # 先调入需要的模块 import numpy as np import matplotlib.pyplot as plt from sklearn import svm import ...

  3. 利用原生态的(System.Web.Extensions)JavaScriptSerializer将mvc 前台提交到controller序列化复杂对象

    主要代码如下: public JsonResult Test() { string s = Request.Form.ToString(); JavaScriptSerializer jss = ne ...

  4. hive sql 效率提升

    转 :  http://www.cnblogs.com/xd502djj/p/3799432.html hive的查询注意事项以及优化总结 . Hive是将符合SQL语法的字符串解析生成可以在Hado ...

  5. 拓扑排序-有向无环图(DAG, Directed Acyclic Graph)

    条件: 1.每个顶点出现且只出现一次. 2.若存在一条从顶点 A 到顶点 B 的路径,那么在序列中顶点 A 出现在顶点 B 的前面. 有向无环图(DAG)才有拓扑排序,非DAG图没有拓扑排序一说. 一 ...

  6. ASP.NET 三级联动

    三级联动就是用三个下拉列表框DropDownList,每个里面添加相应的东西,在第一个列表框中选择一个值,第二三个列表框都会根据第一个选择进行相应的变化,在第二个列表框中选择一个值,第三个列表框也会根 ...

  7. JAVA语言 第三周

    第三周,跟随菜鸟教程学习了一些简单的JAVA语法,包括数据类型.变量.修饰符.运算符.循环.数组.继承. 这些在结构中与c++相似,但语法有些不同.在这些方面,我做了一些总结. 开学测试那张卷子,被我 ...

  8. QQ传文件测试要点

    总-分-总 UI:   进度:进度条.百分比.速度.已传文件大小 显示传送文件图标.悬浮有文字 功能入口:图标.菜单项 各种提示:开始传送.各种异常信息的提示.传送结束 给好友传文件.给群传文件 功能 ...

  9. 2018面向对象程序设计(Java)第1周学习指导及要求

    2018面向对象程序设计(Java) 第1周学习指导及要求(2018.8.24-2018.9.2)   学习目标 了解课程上课方式及老师教学要求,掌握课程学习必要的软件工具: 简单了解Java特点及历 ...

  10. OpenCV批量读入(处理)

    #include <windows.h> #include <iostream> #include <opencv2/opencv.hpp> using names ...