FastDfsConfig
@Slf4j
@Configuration
public class FastDfsConfig {
private static final String CONFIG_FILENAME = "fastdfs-client.properties";
@Bean
public TrackerClient trackerClient(){
try {
//全局初始化配置文件
ClientGlobalPower.initByProperties(CONFIG_FILENAME);
//定义TrackerClient,用于请求TrackerServer
//连接tracker
return new TrackerClient();
} catch (Exception e) {
log.error("加载fastDfs配置失败",e);
}
return null;
}
}
FastDfsUtils
@Slf4j
@Component
public class FastDfsUtils {
@Autowired
private TrackerClient trackerClient;
public StorageClient1 init(){
try {
//连接tracker
TrackerServer trackerServer = trackerClient.getConnection();
ProtoCommon.activeTest(trackerServer.getSocket());
//获取Stroage
StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);
//创建stroageClient
ProtoCommon.activeTest(trackerServer.getSocket());
return new StorageClient1(trackerServer,storeStorage);
} catch (IOException e) {
log.error("fastdfs ProtoCommon.activeTest初始化异常",e);
}
return null;
}
/**
* 上传文件
* @param bytes 文件
* @param file_ext_name 扩展名
* @return
*/
public String upload(byte[] bytes,String file_ext_name){
if (StringUtils.isEmpty(file_ext_name))
return null;
final StorageClient1 storageClient = init();
if (storageClient != null){
String fileId = null;
try {
fileId = storageClient.upload_file1(bytes, file_ext_name,null);
return fileId;
} catch (Exception e) {
log.error("上传文件出现异常",e);
}
}
return null;
}
/**
* 删除文件
* @param file_id
* @return
*/
public Integer delete(String file_id){
int count = 0;
final StorageClient1 storageClient = init();
if (storageClient != null){
try {
count = storageClient.delete_file1(file_id);
return count;
} catch (Exception e) {
log.error("删除文件出现异常,file_id:{}",file_id,e);
}
}
return count;
}
}