【Java】阿里云OSS上传、删除文件
阿里云OSS上传、删除文件
编写AliOssConfig:
import lombok.Data;
/**
* <p>DESC: </p>
* <p>VERSION:1.0.0</p>
*/
@Data
public class AliOssConfig {
private String endpoint;
private String accessKey;
private String accessSecret;
private String bucket;
private String defaultFolder="/";
/**
* 文件路径有效天数,天
*/
private int expireDate=36500;
/**
* 访问类型0:public,1:私有
*/
private int accessType=0;
}
具体实现类:
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.file.FileSystemException;
import java.util.List;
import java.util.Objects;
/**
* <p>阿里上传文件</p>
*
* @Description 阿里上传文件
*/
@Component("AliFileProcessingImpl")
@Slf4j
public class AliFileProcessingImpl implements FileProcessingService {
@Autowired
private SysSettingService sysSettingService;
private AliOssConfig aliOssConfig = new AliOssConfig();
//todo 这里可以直接写在配置文件中使用@value ,这里就不写sysSettingService里面的相关方法了
public AliOssConfig getSettingConfig(String type) {
List<SysSetting> data = sysSettingService.getConfigList(type).getData();
data.forEach(setting -> {
String key = setting.getKey();
String value = setting.getValue();
// 根据枚举匹配对应的方法调用
OssConfigKeyEnum.fromKey(key)
.ifPresent(action -> action.apply(aliOssConfig, value));
});
return aliOssConfig;
}
@Override
public String uploadFile(MultipartFile file) throws IOException {
String contentType = file.getContentType();
byte[] fileBytes = file.getBytes();
String fileMd5 = getFileMd5(fileBytes);
String dbFile = getFileDO(fileMd5);
if (Objects.nonNull(dbFile)) {
return dbFile;
}
String fileName = file.getOriginalFilename();
String fileType = FileUtil.getSuffixName(fileName);
if (FileTypeEnum.getSuffixType(fileType) == null) {
throw new FileSystemException(BizCodeEnum.UNSUPPORTED_FILE_TYPE.getMessage());
}
fileName = UUIDUtil.get32Uuid() + CommonSymbols.POINT + fileType;
String url = upload(fileName, file.getBytes());
log.info("OSS->{}", "上传的文件返回的地址:" + url);
return url;
}
public Integer checkFileType(MultipartFile file) {
String contentType = file.getContentType();
if (contentType == null) {
return -1;
}
if (contentType.startsWith("image/")) {
return 1;
} else if (contentType.startsWith("video/")) {
return 2;
} else {
return 3;
}
}
/**
* 将文件上传到ali oss
*
* @param fileName 文件名
* @param bytes 文件字节数据
* @return 文件地址
*/
private String upload(String fileName, byte[] bytes) {
aliOssConfig = getSettingConfig(SystemSettingTypeConstant.OSS);
log.info("info={}", "开始文件上传");
OSS oss = initOss();
oss.putObject(aliOssConfig.getBucket(), fileName, new ByteArrayInputStream(bytes));
shutdown(oss);
return CommonSymbols.HTTPS +
aliOssConfig.getBucket() +
CommonSymbols.POINT +
aliOssConfig.getEndpoint() +
CommonSymbols.SLASH +
fileName;
}
/**
* ali oss删除文件
*
* @param filename
* @return
*/
public boolean delete(String filename) {
aliOssConfig = getSettingConfig(SystemSettingTypeConstant.OSS);
// 填写文件完整路径。文件完整路径中不能包含Bucket名称。
String objectName = filename;
OSS ossClient = new OSSClientBuilder().build(aliOssConfig.getEndpoint(), aliOssConfig.getAccessKey(), aliOssConfig.getAccessSecret());
try {
// 删除文件或目录。如果要删除目录,目录必须为空。
ossClient.deleteObject(aliOssConfig.getBucket(), objectName);
return true;
} catch (OSSException oe) {
log.error("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason."
+ " \n Error Message:" + oe.getErrorMessage()
+ " \n Error Code:" + oe.getErrorCode()
+ " \n Request ID:" + oe.getRequestId()
+ " \n Host ID:" + oe.getHostId()
);
} catch (ClientException ce) {
log.error("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network."
+ "Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return false;
}
/**
* 关闭oss连接
*
* @param oss 打开的oss对象
*/
private void shutdown(OSS oss) {
if (oss != null) {
oss.shutdown();
}
}
/**
* 初始化启动oss连接
*
* @return OSS
*/
private OSS initOss() {
return new OSSClientBuilder().build(aliOssConfig.getEndpoint(), aliOssConfig.getAccessKey(),
aliOssConfig.getAccessSecret());
}
private String getFileMd5(byte[] fileBytes) {
return DigestUtil.md5Hex(fileBytes);
}
private String getFileDO(String md5) {
LambdaQueryWrapper<SysAttachment> query = new LambdaQueryWrapper<>();
query.eq(SysAttachment::getSha1, md5);
List<SysAttachment> list = attachmentService.list(query);
if (!CollectionUtils.isEmpty(list)) {
return list.get(0).getUrl();
}
return null;
}
}