【FastDFS】06 SpringBoot实现上传
创建SpringBoot工程:

再导入所需要的依赖:
<dependency>
<groupId>net.oschina.zcx7878</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27.0.0</version>
</dependency> <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
创建上传业务层程序:
package cn.dzz.fastdfs.service; import org.apache.commons.lang3.StringUtils;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile; import java.util.HashMap;
import java.util.Map; /**
* @author DaiZhiZhou
* @file Boot-With-FastDFS
* @create 2020-08-13 8:55
*/ // @PropertySource()
@Component
public class UploadService { @Value("${fastdfs.tracker_servers}")
private String tracker_servers; @Value("${fastdfs.connect_timeout_in_seconds}")
private int connect_timeout; @Value("${fastdfs.network_timeout_in_seconds}")
private int network_timeout; @Value("${fastdfs.charset}")
private String charset; public Map<String,Object> upload(MultipartFile multipartFile) {
if (multipartFile == null) {
throw new RuntimeException("文件不能为空");
}
// 上传至fastDFS, 返回文件id
String fileId = this.fdfsUpload(multipartFile);
if (StringUtils.isEmpty(fileId)) {
System.out.println("上传失败");
throw new RuntimeException("上传失败");
}
Map<String, Object> map=new HashMap<>();
map.put("code",200);
map.put("msg","上传成功");
map.put("fileId",fileId);
return map;
} /**
* 上传至fastDFS
* @param multipartFile
* @return 文件id
*/
private String fdfsUpload(MultipartFile multipartFile) {
// 1. 初始化fastDFS的环境
initFdfsConfig();
// 2. 获取trackerClient服务
TrackerClient trackerClient = new TrackerClient();
try {
TrackerServer trackerServer = trackerClient.getConnection();
// 3. 获取storage服务
StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);
// 4. 获取storageClient
StorageClient1 storageClient1 = new StorageClient1(trackerServer, storeStorage);
// 5. 上传文件 (文件字节, 文件扩展名, )
// 5.1 获取文件扩展名
String originalFilename = multipartFile.getOriginalFilename();
String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
// 5.2 上传
String fileId = storageClient1.upload_file1(multipartFile.getBytes(), extName, null);
return fileId;
} catch (Exception e) {
System.out.println(e);
return null;
}
} /**
* 初始化fastDFS的环境
*/
private void initFdfsConfig() {
try {
ClientGlobal.initByTrackers(tracker_servers);
ClientGlobal.setG_connect_timeout(connect_timeout);
ClientGlobal.setG_network_timeout(network_timeout);
ClientGlobal.setG_charset(charset);
} catch (Exception e) {
System.out.println(e);
}
}
}
创建上传控制器:
package cn.dzz.fastdfs.controller; import cn.dzz.fastdfs.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile; import java.util.Map; /**
* @author DaiZhiZhou
* @file Boot-With-FastDFS
* @create 2020-08-13 8:58
*/ @RestController
@RequestMapping("upload")
public class UploadController { @Autowired
private UploadService uploadService; /**
* 作上传
*/
@RequestMapping("doUpload")
public Map<String,Object> doUpload(MultipartFile mf){
System.out.println(mf.getOriginalFilename());
Map<String, Object> map = uploadService.upload(mf);
return map;
}
}
在static目录中创建index.html用于上传测试:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body> <h1>文件上传</h1>
<hr>
<form action="/upload/doUpload" method="post" enctype="multipart/form-data">
<input type="file" name="mf">
<input type="submit" value="上传">
</form> </body>
</html>
运行SpringBoot进行测试:

测试成功:

查看文件位置也可以被访问到:

上传文件实现方式二:
更改依赖:
<!-- https://mvnrepository.com/artifact/com.github.tobato/fastdfs-client -->
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.26.7</version>
</dependency>
创建一个配置类UploadProperties
package cn.dzz.fastdfs.config; import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; import java.util.List; /**
* @author DaiZhiZhou
* @file Boot-With-FastDFS
* @create 2020-08-13 9:10
*/ @Data
@Component
@ConfigurationProperties(prefix = "upload")
public class UploadProperties {
private String baseUrl;
private List<String> allowTypes;
}
更改之前的yml配置:
fdfs:
so-timeout: 2500 # 读取时间
connect-timeout: 600 # 连接超时时间
thumb-image: # 缩略图
width: 100
height: 100
tracker-list: # tracker服务配置地址列表
- 服务器或者虚拟机IP:22122
upload:
base-url: http://服务器或者虚拟机IP/
allow-types:
- image/jpeg
- image/png
- image/bmp
- image/gif
编写UploadProperties.java
package cn.dzz.config; import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties; import java.util.List; /**
* @author DaiZhiZhou
* @file fdfs
* @create 2020-08-13 9:33
*/
@ConfigurationProperties(prefix = "upload")
@Data
public class UploadProperties {
private String baseUrl;
private List<String> allowTypes;
}
业务层:
package cn.dzz.service; import cn.dzz.config.UploadProperties;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException; /**
* @author DaiZhiZhou
* @file fdfs
* @create 2020-08-13 9:34
*/ @Component
@EnableConfigurationProperties(UploadProperties.class)
public class UploadService {
private Log log= LogFactory.getLog(UploadService.class); @Autowired
private FastFileStorageClient storageClient; @Autowired
private UploadProperties prop; public String uploadImage(MultipartFile file) {
// 1、校验文件类型
String contentType = file.getContentType();
if (!prop.getAllowTypes().contains(contentType)) {
throw new RuntimeException("文件类型不支持");
}
// 2、校验文件内容
try {
BufferedImage image = ImageIO.read(file.getInputStream());
if (image == null || image.getWidth() == 0 || image.getHeight() == 0) {
throw new RuntimeException("上传文件有问题");
}
} catch (IOException e) {
log.error("校验文件内容失败....{}", e);
throw new RuntimeException("校验文件内容失败"+e.getMessage());
} try {
// 3、上传到FastDFS
// 3.1、获取扩展名
String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
// 3.2、上传
StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);
// 返回路径
return prop.getBaseUrl() + storePath.getFullPath();
} catch (IOException e) {
log.error("【文件上传】上传文件失败!....{}", e);
throw new RuntimeException("【文件上传】上传文件失败!"+e.getMessage());
}
}
}
控制器:
package cn.dzz.controller; import cn.dzz.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import java.util.HashMap;
import java.util.Map; /**
* @author DaiZhiZhou
* @file fdfs
* @create 2020-08-13 9:35
*/
@RequestMapping("upload")
@RestController
public class UploadController { @Autowired
private UploadService uploadService; @RequestMapping("doUpload")
public Map<String,Object> doUpload(MultipartFile multipartFile) {
System.out.println(multipartFile.getOriginalFilename());
Map<String, Object> map = new HashMap<>();
String filePath = uploadService.uploadImage(multipartFile);
map.put("filePath", filePath);
return map;
} }
还是一样的上传页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body> <h1>文件上传</h1>
<hr>
<form action="/upload/doUpload" method="post" enctype="multipart/form-data">
<input type="file" name="mf">
<input type="submit" value="上传">
</form> </body>
</html>
运行发现空指针异常,检查发现表单名称没对上,SpringMVC就无法转换了

<input type="file" name="multipartFile">
再次测试:

访问:

【FastDFS】06 SpringBoot实现上传的更多相关文章
- SpringBoot整合Fastdfs,实现图片上传(IDEA)
我们部署Fastdfs,就是为了实现文件的上传. 现在使用idea整合Fastdfs,实现图片上传 部署环境:Centos7部署分布式文件存储(Fastdfs) 利用Java客户端调用FastDFS ...
- 如何在SpringBoot当中上传多个图片或者上传单个图片 工具类
如何在SpringBoot当中上传多个图片[上传多个图片 ] 附赠工具类 1.SpringBoot 上传图片工具类 public class SpringUploadUtil { /*** * 上传图 ...
- 补习系列(11)-springboot 文件上传原理
目录 一.文件上传原理 二.springboot 文件机制 临时文件 定制配置 三.示例代码 A. 单文件上传 B. 多文件上传 C. 文件上传异常 D. Bean 配置 四.文件下载 小结 一.文件 ...
- Springboot 文件上传(带进度条)
1. 相关依赖 pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http ...
- SpringBoot学习笔记(8)-----SpringBoot文件上传
直接上代码,上传文件的前端页面: <body> <form action="/index/upload" enctype="multipart/form ...
- 【使用篇二】SpringBoot文件上传(5)
一.单个文件上传 1. 在static目录下创建upload.html <!DOCTYPE html> <html> <head> <meta charset ...
- 【SpringBoot】07.SpringBoot文件上传
SpringBoot文件上传 1.编写html文件在classpath下的static中 <!DOCTYPE html> <html> <head> <met ...
- springboot项目上传存储图片到七牛云服务器
springboot项目上传存储图片到七牛云服务器 问题描述: 当图片存在本地时会出现卡顿的现象.比如一篇图文混排的文章,如果图片没有加载完,可能整个文章都显示不出来,因为它们都是用的同一个服务器. ...
- SpringBoot整合FastDFS实现图片的上传
文件的上传和预览在web开发领域是随处可见,存储的方式有很多,本文采用阿里巴巴余庆大神开发的FastDFS进行文件的存储,FastDFS是一个分布式文件存储系统,可以看我上一篇博文,有安装和配置教程 ...
- 二、SpringBoot实现上传文件到fastDFS文件服务器
上篇文章介绍了如何使用docker安装fastDFS文件服务器,这一篇就介绍整合springBoot实现文件上传到fastDFS文件服务器 1.pom.xml文件添加依赖 <!-- 连接fast ...
随机推荐
- css圆圈慢慢放大
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8 ...
- LeetCode 688. Knight Probability in Chessboard “马”在棋盘上的概率 (C++/Java)
题目: On an NxN chessboard, a knight starts at the r-th row and c-th column and attempts to make exact ...
- 剑指Offer-53.表示数值的字符串(C++/Java)
题目: 请实现一个函数用来判断字符串是否表示数值(包括整数和小数).例如,字符串"+100","5e2","-123","3.14 ...
- 知名火锅连锁企业,IT 团队如何在数千家门店中先于用户发现故障
该知名火锅连锁企业是中国领先的餐饮企业,上千家门店遍布全球,由于门店餐饮行业的特殊性,需要靠前部署服务,所以在每家餐厅中,会部署相应的服务器,及相应 IT 设备,本地会运行POS.会员.下单等业务.公 ...
- 利用.htaccess绑定子域名到子目录
Tips:当你看到这个提示的时候,说明当前的文章是由原emlog博客系统搬迁至此的,文章发布时间已过于久远,编排和内容不一定完整,还请谅解` 利用.htaccess绑定子域名到子目录 日期:2018- ...
- FreeRTOS简单内核实现6 优先级
0.思考与回答 0.1.思考一 如何实现 RTOS 内核支持多优先级? 因为不支持优先级,所以所有的任务都插入了一个名为 pxReadyTasksLists 的就绪链表中,相当于所有任务的优先级都是一 ...
- Windows10(or windows11) Hyper-V 创建虚拟交换机后宿主机上传速度变特别慢的问题解决
问题 我在我的win11上启用了Hyper-v,装了个虚拟机跑了个CentOS7.6,为了让centos和宿主机通信在同个网段搞了个桥接网络,网络环境如下 然后我测试一个文件上传功能的时候发现网络上传 ...
- python实现推送消息到微信公众号
使用到库: Requests 实现方式: 微信已开放了对应的接口,直接通过python的requests库,发起请求,实现推送消息到公众号 微信公众号准备: 1.没有注册微信公众号,可以使用微信提供的 ...
- 解析QAnything启动命令过程
一.启动命令过程日志 启动命令bash ./run.sh -c local -i 0 -b hf -m Qwen-1_8B-Chat -t qwen-7b-chat.输入日志如下所示: root@MM ...
- 3.8折年终钜惠,RK3568J国产工业评估板
3.8折年终钜惠,RK3568J国产工业评估板活动火热进行中,错过等一年! -核心板国产化率100%,提供报告-瑞芯微四核ARM Cortex-A55@1.8GHz-4K视频解码.1080P视频编码. ...