一、引入FastDFS客户端依赖:
二、在application.yml配置文件中配置FastDFS客户端,包括连接超时、网络超时、字符集等参数的设置以及FastDFS服务器的地址和端口号等信息。
三、使用@Autowired注入FastDFS客户端对象,在需要上传或下载文件的控制器中调用FastDFS提供的API接口。具体上传、下载的流程如下:
- 上传文件:调用FastDFS的uploadFile方法将文件流上传至FastDFS服务器,并返回文件存储路径(StorePath对象)。通过访问路径即可获取文件内容。
- 下载文件:根据上传时返回的访问路径解析出文件所在的组名(group)和文件名(path),然后调用FastDFS的downloadFile方法下载文件,方法会返回一个字节数组。将字节数组写回响应中即可完成文件下载。
-
根据返回的StorePath对象构造文件的访问路径。访问路径以http://+FastDFS服务器IP+端口号+/+group+/+path的形式组成,其中group是FastDFS服务器上的分组名称, path是文件在分组里的路径和文件名组成的字符串。
-
将文件流或字节数组返回给客户端,完成文件的上传或下载操作。
1.引入FastDFS依赖
在pom.xml文件中加入FastDFS客户端的依赖:
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.27.2</version>
</dependency>
2.配置FastDFS客户端
在application.yml配置文件中加入FastDFS客户端的配置,例如:
# fastdfs配置
fdfs:
# 请求连接池配置
soTimeout: 1500
connectTimeout: 600
tracker-list:
- 192.168.10.100:22122
- 192.168.10.101:22122
上传文件的控制器方法:
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileController {
@Autowired
private FastFileStorageClient storageClient;
@PostMapping("/upload")
public String upload(@RequestPart MultipartFile file) throws IOException {
StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
FilenameUtils.getExtension(file.getOriginalFilename()), null);
return storePath.getFullPath();
}
}
下载文件的控制器方法:
import com.github.tobato.fastdfs.domain.fdfs.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.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class DownloadController {
@Autowired
private FastFileStorageClient storageClient;
@GetMapping("/download")
public ResponseEntity<byte[]> download(@RequestParam String filepath) throws IOException {
StorePath storePath = StorePath.parseFromUrl(filepath);
byte[] content = storageClient.downloadFile(storePath.getGroup(), storePath.getPath(),
new DownloadByteArray());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", storePath.getFilename());
headers.setContentLength(content.length);
return new ResponseEntity<>(content, headers, HttpStatus.OK);
}
}
其中@Autowired注入了FastFileStorageClient,使用该客户端的uploadFile方法进行文件上传,通过downloadFile的方式下载指定路径下的文件。
注意,上传时返回的storePath包含了group和path,用于构造文件访问路径。下载时需要从访问路径中解析出group和path参数再进行下载。