0
点赞
收藏
分享

微信扫一扫

springboot集成fastdfs使用com.github.tobato的fastdfs-client内附Demo下载(2021-06-18)


Demo下载:公众号:知识浅谈 后台回复 fastdfsdemo 获取下载地址

具体服用过程如下,服用之前确保fdfs_trackerd fdfs_storaged nginx 配置好并且已经运行

[root@iZhp333b21cruky4l17cm0Z /]# service fdfs_trackerd status
● fdfs_trackerd.service - LSB: FastDFS tracker server
Loaded: loaded (/etc/rc.d/init.d/fdfs_trackerd; bad; vendor preset: disabled)
Active: active (running) since Thu 2021-06-17 20:08:51 CST; 14h ago
Docs: man:systemd-sysv-generator(8)
[root@iZhp333b21cruky4l17cm0Z /]# service fdfs_storaged status
● fdfs_storaged.service - LSB: FastDFS storage server
Loaded: loaded (/etc/rc.d/init.d/fdfs_storaged; bad; vendor preset: disabled)
Active: active (running) since Fri 2021-06-18 09:12:46 CST; 1h 21min ago
Docs: man:systemd-sysv-generator(8)
[root@iZhp333b21cruky4l17cm0Z /]# service nginx status
Redirecting to /bin/systemctl status nginx.service
● nginx.service - nginx - high performance web server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
Active: active (running) since Wed 2021-06-16 16:03:19 CST; 1

创建springboot项目

具体的创建流程就不列出来了,

引入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.englishcode</groupId>
<artifactId>fastdfsdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>fastdfsdemo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--fastdfs依赖-->
<!-- https://mvnrepository.com/artifact/com.github.tobato/fastdfs-client -->
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.27.2</version>
</dependency>



<!--thymeleaf依赖-->
<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-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>

</project>

修改配置文件

#fastdfs 配置
fdfs:
# 读取时间
so-timeout: 1500
# 连接超时时间
connect-timeout: 600
# 缩略图
thumb-image:
width: 150
height: 150
# Tracker服务,确保tracker storage nginx已经启动
tracker-list:
- 39.104.67.142:22122

创建配置类

package com.englishcode.fastdfsdemo.config;

import com.github.tobato.fastdfs.FdfsClientConfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy;

/**
* @author: YinLei
* Package: com.englishcode.fastdfsdemo.config
* @date: 2021/6/18 10:02
* @Description: fastdfs配置类
* @version: 1.0
*/
@Configuration
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FdfsConfig {

}

创建工具类

package com.englishcode.fastdfsdemo.utils;

import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
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 java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;

/**
* @author: YinLei
* Package: com.englishcode.fastdfsdemo.utils
* @date: 2021/6/18 10:03
* @Description: Fastdfs客户端工具类
* @version: 1.0
*/
@Component
public class FdfsClientWrapper {

@Autowired
private FastFileStorageClient fastFileStorageClient;

public String uploadFile(MultipartFile file) throws IOException {
if (file != null) {
byte[] bytes = file.getBytes();
long fileSize = file.getSize();
String originalFilename = file.getOriginalFilename();
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", LocalDateTime.now().toString()));
metaDataSet.add(new MetaData("Author","Layne"));
StorePath storePath = fastFileStorageClient.uploadFile(bais, fileSize, extension, metaDataSet);
return storePath.getFullPath();
}

/**
* 下载文件
*
* @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);
}
}

}

创建form文件上传表单{/resource/template下}

<!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>

创建测试controller

package com.englishcode.fastdfsdemo.controller;

import com.englishcode.fastdfsdemo.utils.FdfsClientWrapper;
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 javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
* @author: YinLei
* Package: com.englishcode.fastdfsdemo.controller
* @date: 2021/6/18 10:07
* @Description: 文件上传下在删除测试Controller
* @version: 1.0
*/
@Controller
public class FileUploadController {

private static Logger log = LoggerFactory.getLogger(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) {
log.error("上传文件异常:{}", 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=" + URLEncoder.encode(fileName, "UTF-8"));
response.setCharacterEncoding("UTF-8");
if (bytes != null) {
outputStream = response.getOutputStream();
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 "删除成功";
}

}

测试

  • 文件上传
    浏览器访问:http://localhost:8080/,选择一种图片,点击提交,记录返回的文件路径filrPath(卷名+文件名)。
  • 文件浏览
    浏览器访问:http://ip:8888/[filePath] //这个地址是storage所在服务器的ip,filePath为上传之后返回的遗传字符串filePath。
  • 文件下载(下载的文件名为:fdfs.jpg)
    浏览器访问:http://localhost:8080/download?filePath=[filePath]
  • 文件删除
    浏览器访问:http://localhost:8080/delete?filePath=[filePath]


举报

相关推荐

0 条评论