1.maven
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.27.2</version>
</dependency>
配置类
@Configuration
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FdfsConfig {
}
工具类
@Component
public class FdfsClientUtils {
@Autowired
private FastFileStorageClient fastFileStorageClient;
public String upload(MultipartFile myfile) throws Exception{
//文件名
String originalFilename = myfile.getOriginalFilename().substring(myfile.getOriginalFilename().lastIndexOf(".") + 1);
// 文件扩展名
String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
StorePath storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(myfile.getInputStream(), myfile.getSize(),originalFilename , null);
String path = storePath.getFullPath();
return path;
}
/**
* 下载文件
*
* @param filePath 文件路径
* @return 文件字节
* @throws IOException
*/
public byte[] downloadFile(String filePath) throws IOException {
byte[] bytes = null;
if (!StringUtils.isEmpty(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.isEmpty(filePath)) {
fastFileStorageClient.deleteFile(filePath);
}
}
}
测试一下
/**
* 上传文件
*
* @param file 文件
* @return 文件路径
*/
@RequestMapping(value = "upload")
@ResponseBody
public String uploadFile(@RequestParam("file") MultipartFile file) {
String filePath = null;
try {
filePath = fdfsClientWrapper.upload(file);
} catch (Exception e) {
log.error("上传文件异常:{}", e);
return "上传文件失败";
}
return filePath;
}
解决报错com.github.tobato.fastdfs.exception.FdfsConnectException: 无法获取服务端连接资源:can’t create connection to/x.xxx.x.xx:0
//FDFS 获取到的端口为0
@Primary
@Component("customizeTrackerClient")
public class CustomizeTrackerClient extends DefaultTrackerClient {
private static final int DEFAULT_PORT = 23000;
public StorageNode getStoreStorage() {
StorageNode res = super.getStoreStorage();
res.setPort(getPort(res.getPort()));
return res;
}
public StorageNode getStoreStorage(String groupName) {
StorageNode res = super.getStoreStorage(groupName);
res.setPort(getPort(res.getPort()));
return res;
}
public StorageNodeInfo getFetchStorage(String groupName, String filename) {
StorageNodeInfo res = super.getFetchStorage(groupName, filename);
res.setPort(getPort(res.getPort()));
return res;
}
public StorageNodeInfo getUpdateStorage(String groupName, String filename) {
StorageNodeInfo res = super.getUpdateStorage(groupName, filename);
res.setPort(getPort(res.getPort()));
return res;
}
private int getPort(int port){
if(port == 0){
return DEFAULT_PORT;
}
return port;
}
}