Fastdfs的安装,请根据网络上的文章以及参考余庆老师github上的install,自行摸索,本文不在赘述
余庆老师的github地址
Mafly的fastdfs安装指南
下面进入正题:
1.在pom.xml中添加如下依赖(这里没有直接选用余庆老师提供的fastdfs-client-java
)
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.25.2-RELEASE</version>
</dependency>
2.添加配置信息application.yml
fdfs:
soTimeout: 1500
connectTimeout: 600
thumbImage: #缩略图生成参数
width: 150
height: 150
trackerList: #TrackerList参数,支持多个
xx.xx.xxx.xx:22122 #请更改为自己的Tracker服务地址
3.多文件上传,下载
文件上传时,直接调用FastFileStorageClient.uploadFile()方法即可。
但是下载时,如果单单调用FastFileStorageClient.downloadFile()方法,那么下载下来的文件名对用户会很不友好,本例将下载返回原名称。
@RestController
public class FastdfsController {
@Autowired
FastFileStorageClient fastFileStorageClient;
/**
* 多文件上传
* @param files
* @return
* @throws IOException
*/
@PostMapping(value = "/upload",produces = "application/json;charset=UTF-8")
public bool uploadFilesWithFastdfs(@RequestParam("file") MultipartFile[] files)throws IOException{
List<FileInfo> fileInfoList = new ArrayList<>();
for(int i = 0; i<files.length;i++){
MultipartFile multipartFile = files[i];
String fileName = multipartFile.getOriginalFilename();
StorePath storePath = fastFileStorageClient.uploadFile(multipartFile.getInputStream(),multipartFile.getSize(),fileName.substring(fileName.lastIndexOf(".")+1),null);
//真实的情况会将数据信息进行保存,包含的信息(文件名,存储路径,是谁的附件等信息),那么入库的过程我就不说了
}
return true;
}
/**
* 单文件下载
* @param id
* @param httpServletResponse
* @throws MalformedURLException
*/
@GetMapping(value = "/download/{id}")
public void downloadFilesWithFastdfs(@PathVariable String id,HttpServletResponse httpServletResponse) throws MalformedURLException {
//操作数据库,读取文件上传时的信息
FileInfo fileInfo = service.getFileInfo(id);
if(fileInfo!=null){
try {
String fileName = URLEncoder.encode(fileInfo.getFileName(),"UTF8");
String fileUrl = fileInfo.getFileUrl();
String filepath = fileUrl.substring(fileUrl.lastIndexOf("group1/")+7);
DownloadByteArray callback = new DownloadByteArray();
byte[] b = fastFileStorageClient.downloadFile("group1", filepath,callback);
httpServletResponse.reset();
httpServletResponse.setContentType("application/x-download");
httpServletResponse.addHeader("Content-Disposition" ,"attachment;filename=\"" +fileName+ "\"");
httpServletResponse.getOutputStream().write(b);
service.updateDownloadCount(id);
httpServletResponse.getOutputStream().close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
最后,文件删除也很简单
调用fastFileStorageClient.deleteFile()即可。