java
整合fdfs
文件服务器
1. 服务器fastdfs
搭建
2. java
代码部分
2.1 引入相关依赖包
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.26.5</version>
</dependency>
2.2 FDFS
配置类
@Configuration
@Import(FdfsClientConfig.class) // 导入FastDFS-Client组件
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) // 解决jmx重复注册bean的问题
public class FdfsConfiguration {
}
2.3 配置文件
# 分布式文件系统fastdfs配置
fdfs:
# socket连接超时时长
soTimeout: 1500
# 连接tracker服务器超时时长
connectTimeout: 600
# nginx 访问的地址和端口
reqHost: 114.55.164.189
reqPort: 80
pool:
# 从池中借出的对象的最大数目
max-total: 153
# 获取连接时的最大等待毫秒数100
max-wait-millis: 102
# 缩略图生成参数,可选
thumbImage:
width: 150
height: 150
# 跟踪服务器tracker_server请求地址,支持多个,这里只有一个,如果有多个在下方加- x.x.x.x:port
trackerList:
- 114.55.164.189:22122
#
# 存储服务器storage_server访问地址
web-server-url: http://114.55.164.189:80/
2.4 读取配置文件的实体类
@Data
@ConfigurationProperties(prefix = "fdfs",ignoreInvalidFields = true)
@Slf4j
public class FastdfsProperties implements InitializingBean {
private String reqHost;
private String reqPort;
private String webServerUrl;
private String soTimeout;
@Override
public void afterPropertiesSet() throws Exception {
log.debug("fdfs.reqHost is {},fdfs.reqPort is {},fdfs.webServerUrl is {}",getReqHost(),getReqPort(),getWebServerUrl());
if (StringUtils.isBlank(getReqHost())) {
throw new IllegalStateException("Property \"fdfs.reqHost\" cannot be blank");
}
if (StringUtils.isBlank(getReqPort())) {
throw new IllegalStateException("Property \"fdfs.reqPort\" cannot be blank");
}
if (StringUtils.isBlank(getWebServerUrl())) {
throw new IllegalStateException("Property \"fdfs.webServerUrl\" cannot be blank");
}
if (StringUtils.isBlank(getSoTimeout())) {
throw new IllegalStateException("Property \"fdfs.soTimeout\" cannot be blank");
}
}
}
「注意启动类需要添加自动加载配置类注解」 @EnableConfigurationProperties({ApplicationProperties.class,FastdfsProperties.class})
2.5 工具类
@Component
public class FastDFSClient {
private Logger log = LoggerFactory.getLogger(FastDFSClient.class);
@Autowired
FastdfsProperties fastdfsProperties;
@Autowired
private FastFileStorageClient storageClient;
@Autowired
private ThumbImageConfig imageConfig; //创建缩略图的
@Autowired
private TrackerClient trackerClient;
/**
* 简单文件上传
* @param file
* @return
*/
public String upload (MultipartFile file){
String fileName = file.getOriginalFilename();
try {
InputStream inputStream= file.getInputStream();
long size = file.getSize();
StorePath path = storageClient.uploadFile(inputStream,size,fileName.substring(fileName.lastIndexOf(".")+ 1), null);
return getResAccessUrl(path);
} catch (IOException e) {
e.printStackTrace();
log.error(e.toString());
return null;
}
}
/**
* 删除指定文件
* @param url
*/
public void delFile (String url){
storageClient.deleteFile(url);
}
/**
* 文件下载
* @param fileUrl
* @return
* @throws IOException
*/
public byte[] downloadFile(String fileUrl) throws IOException {
fileUrl = fileUrl.replaceAll(fastdfsProperties.getWebServerUrl(),"");
String group = fileUrl.substring(0, fileUrl.indexOf("/"));
String path = fileUrl.substring(fileUrl.indexOf("/") + 1);
DownloadByteArray downloadByteArray = new DownloadByteArray();
byte[] bytes = storageClient.downloadFile(group,path, downloadByteArray);
return bytes;
}
/**
* 获取文件路径
* @param path
* @return
*/
private String getResAccessUrl(StorePath path) {
String fileUrl = "http://" + fastdfsProperties.getReqHost() + ":" + fastdfsProperties.getReqPort() + "/" + path.getFullPath();
return fileUrl;
}
}
2.6 测试
@RestController
@RequestMapping("/file")
@Api(tags = "文件管理")
public class UploadController {
@Autowired
private FastDFSClient fastDFSClient;
@ApiOperation(value = "文件上传")
@RequestMapping(value = "/upload" ,method = RequestMethod.POST)
public Result upload(
@RequestParam("file") MultipartFile file
){
if(file == null || file.isEmpty()){
return new Result(RetCode.PARAM_ERROR.getCode(),RetCode.PARAM_ERROR.getMsg(),null);
}
String path = fastDFSClient.upload(file);
return new Result(RetCode.SUCCESS.getCode(),RetCode.SUCCESS.getMsg(),path);
}
@ApiOperation(value = "删除文件")
@RequestMapping(value = "/del" ,method = RequestMethod.GET)
@ApiImplicitParams({
@ApiImplicitParam(value = "文件全路径" ,name = "url" ,required = true,dataType = "String",paramType = "query")
})
public Result delFile(String url){
if(url == null || url.equals("")){
return new Result(RetCode.PARAM_ERROR.getCode(),RetCode.PARAM_ERROR.getMsg(),null);
}
try {
fastDFSClient.delFile(url);
return new Result(RetCode.SUCCESS.getCode(),RetCode.SUCCESS.getMsg(),null);
} catch (Exception e){
return new Result(RetCode.PARAM_VALUE_ERROR.getCode(),RetCode.PARAM_VALUE_ERROR.getMsg(),null);
}
}
@ApiOperation(value = "文件下载")
@GetMapping("/downLoad")
public ResponseEntity<byte []> downLoadFile(
@ApiParam(value = "文件路径",required = true) @RequestParam(value = "url" ,required = true) String url
) {
try {
byte[] bytes = fastDFSClient.downloadFile(url);
String fileName =url.substring(url.lastIndexOf("/" +1));
fileName = new String(fileName.getBytes("utf-8"),"ISO_8859_1");
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
httpHeaders.setContentDispositionFormData("attachment", fileName);
return new ResponseEntity<byte[]>(bytes,httpHeaders,HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
![alt](https://imgkr2.cn-bj.ufileos.com/fd70cffb-409f-45f3-97d5-ec886220f654.png?UCloudPublicKey=TOKEN_8d8b72be-579a-4e83-bfd0-5f6ce1546f13&Signature=cvnTXxvkNTaSerTPakqaDkct%252F%252BA%253D&Expires=1599629092)
![alt](https://imgkr2.cn-bj.ufileos.com/57bada3a-efdc-4a51-9c0b-61e2417dfc2e.png?UCloudPublicKey=TOKEN_8d8b72be-579a-4e83-bfd0-5f6ce1546f13&Signature=vwrKOuxGMheoWCVSQwMRxnJMx1k%253D&Expires=1599629114)
![alt](https://imgkr2.cn-bj.ufileos.com/759f39c3-9878-42ec-b757-7ffbed31cd5b.png?UCloudPublicKey=TOKEN_8d8b72be-579a-4e83-bfd0-5f6ce1546f13&Signature=kDBa8FRDi%252BRElWZ3si1fTi2bYW4%253D&Expires=1599629144)