SpringBoot集成基于tobato的fastdfs-client实现⽂件上传下载和
删除
1. 简介
  基于tobato的fastdfs-client是⼀个功能完善的FastDFS客户端⼯具,它是在FastDFS作者YuQing发布的客户端基础上进⾏了⼤量的重构,提供了上传、下载、删除、⽣成缩略图等API。
2. 安装FastDFS
3. ⽰例代码
创建⼯程
修改l
<project xmlns="/POM/4.0.0"
xmlns:xsi="/2001/XMLSchema-instance"
xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.c3stones</groupId>
<artifactId>spirng-boot-fastdfs-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spirng-boot-fastdfs-demo</name>
<description>Spring Boot FastDFS Demo</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.8.RELEASE</version>
<relativePath />
</parent>
<dependencies>
<dependency>
<groupId>bato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.26.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<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>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
创建配置⽂件l
#fastdfs 配置
fdfs:
# 读取时间
so-timeout: 1500
# 连接超时时间
connect-timeout: 600
# 缩略图
thumb-image:
width: 150
height: 150
# Tracker服务
tracker-list:
- 192.168.0.100:22122
创建配置类
import t.annotation.Configuration;
import t.annotation.EnableMBeanExport;
import t.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy;
import bato.fastdfs.FdfsClientConfig;
/**
* FastDFS Client配置
*
* @author CL
*
*/
@Configuration
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) public class FdfsConfig {
}
创建包装类
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
import org.apachemons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import bato.fastdfs.domain.fdfs.MetaData;
import bato.fastdfs.domain.fdfs.StorePath;
import bato.fastdfs.domain.proto.storage.DownloadByteArray;
import bato.fastdfs.service.FastFileStorageClient;
/
**
* FastDFS客户端包装类
*
* @author CL
*
*/
@Component
public class FdfsClientWrapper {
@Autowired
private FastFileStorageClient fastFileStorageClient;
public String uploadFile(MultipartFile file) throws IOException {
connect下载if (file != null) {
byte[] bytes = Bytes();
long fileSize = Size();
String originalFilename = OriginalFilename();
String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
return this.uploadFile(bytes, fileSize, extension);
}
return null;
}
/**
* ⽂件上传
*
* @param bytes    ⽂件字节
* @param fileSize  ⽂件⼤⼩
* @param extension ⽂件扩展名
* @return 返回⽂件路径(卷名和⽂件名)
*/
public String uploadFile(byte[] bytes, long fileSize, String extension) {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
// 元数据
Set<MetaData> metaDataSet = new HashSet<MetaData>();
metaDataSet.add(new MetaData("dateTime", w().toString()));
StorePath storePath = fastFileStorageClient.uploadFile(bais, fileSize, extension, metaDataSet);  FullPath();
}
/**
* 下载⽂件
*
* @param filePath ⽂件路径
* @return ⽂件字节
* @throws IOException
*/
public byte[] downloadFile(String filePath) throws IOException {
byte[] bytes = null;
if (StringUtils.isNotBlank(filePath)) {
String group = filePath.substring(0, filePath.indexOf("/"));
String path = filePath.substring(filePath.indexOf("/") + 1);
DownloadByteArray byteArray = new DownloadByteArray();
bytes = fastFileStorageClient.downloadFile(group, path, byteArray);
}
return bytes;
}
/**
* 删除⽂件
*
* @param filePath ⽂件路径
*/
public void deleteFile(String filePath) {
if (StringUtils.isNotBlank(filePath)) {
fastFileStorageClient.deleteFile(filePath);
}
}
}
创建⽂件上传Controller
import java.io.IOException;
import java.URLEncoder;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.c3stones.wapper.FdfsClientWrapper;
/**
* ⽂件上传Controller
*
* @author CL
*
*/
@Controller
public class FileUploadController {
private static Logger log = Logger(FileUploadController.class);
@Autowired
private FdfsClientWrapper fdfsClientWrapper;
/**
* 进⼊上传页⾯
*
* @return 路径
*/
@RequestMapping(value = "/")
public String form() {
return "form";
}
/**
* 上传⽂件
*
* @param file ⽂件
* @return ⽂件路径
*/
@RequestMapping(value = "upload")
@ResponseBody
public String uploadFile(MultipartFile file) {
String filePath = null;
try {
filePath = fdfsClientWrapper.uploadFile(file);
} catch (IOException e) {
<("上传⽂件异常:{}", e);
return "上传⽂件失败";
}
return filePath;
}
/**
* 下载⽂件
*
* @param filePath ⽂件路径
* @return
*/
@RequestMapping(value = "download")
public void downloadFile(String filePath, HttpServletResponse response) {
ServletOutputStream outputStream = null;
try {
byte[] bytes = fdfsClientWrapper.downloadFile(filePath);
String fileName = "fdfs.jpg";
response.setHeader("Content-disposition", "attachment;filename=" + de(fileName, "UTF-8"));  response.setCharacterEncoding("UTF-8");
if (bytes != null) {
outputStream = OutputStream();
outputStream.write(bytes);
outputStream.flush();
}
} catch (IOException e) {
log.debug("下载⽂件输出流异常:{}", e);
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
log.debug("下载⽂件关闭流异常:{}", e);
}
}
}
/**
* 删除⽂件
*
* @param filePath ⽂件路径
* @return 删除结果
*/
@RequestMapping(value = "delete")
@ResponseBody
public String deleteFile(String filePath) {
fdfsClientWrapper.deleteFile(filePath);
return "删除成功";
}
}
创建启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* 启动类
*
* @author CL
*
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
在resource下创建templates/form.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>上传⽂件</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
选择⽂件:<input type="file" name="file"><br />
<input type="submit" value="提交">
</form>
</body>
</html>
启动项⽬
4. 测试
⽂件上传
  浏览器访问:,选择⼀种图⽚,点击提交,记录返回的⽂件路径(卷名+⽂件名)。
⽂件浏览
  浏览器访问:
⽂件下载(下载的⽂件名为:fdfs.jpg)
  浏览器访问:
⽂件删除
  浏览器访问:
5. 项⽬地址

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。