FastDFS简介
FastDFS是一个开源的轻量级分布式文件系统,它解决了大容量存储和负载均衡的问题。FastDFS架构包括Tracker server和Storage server。客户端请求Tracker server进行文件上传、下载,Tracker server负责负载均衡和调度,最终由Storage server完成文件上传和下载。
Spring Boot项目集成FastDFS
添加Maven依赖
在你的Spring Boot项目的pom.xml文件中添加FastDFS Java客户端的依赖。例如:
<dependency><groupId>com.github.tobato</groupId><artifactId>fastdfs-client-spring-boot-starter</artifactId><version>最新版本号</version>
</dependency>
注意:这里的版本号应该替换为FastDFS Java客户端的最新稳定版本。
配置FastDFS连接
在Spring Boot的配置文件(如application.properties或application.yml)中添加FastDFS的连接配置。
例如,在application.yml中配置,
fdfs:so-timeout: 1500connect-timeout: 600thumb-image:height: 50width: 50tracker-list:- Tracker服务器地址:端口
创建一个Controller来处理文件上传和下载请求
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;@RestController
@RequestMapping("/file")
public class FileController {@Autowiredprivate FastFileStorageClient storageClient;@PostMapping("/upload")public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {if (file.isEmpty()) {return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("文件为空");}try {StorePath storePath = storageClient.uploadFile(file.getInputStream(),file.getSize(),FileUtils.getExtension(file.getOriginalFilename()),null);return ResponseEntity.ok(storePath.getFullPath());} catch (IOException e) {return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败");}}@GetMapping("/download")public ResponseEntity<byte[]> downloadFile(@RequestParam("group") String group, @RequestParam("path") String path) {if (StringUtils.isEmpty(group) || StringUtils.isEmpty(path)) {return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new byte[0]);}try {byte[] fileContent = storageClient.downloadFile(group, path, null);HttpHeaders headers = new HttpHeaders();headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + path.substring(path.lastIndexOf("/") + 1) + "\"");headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);} catch (IOException e) {return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new byte[0]);}}
}