【Java】阿里云OSS上传、删除文件

server/2025/1/22 23:54:40/

阿里云OSS上传、删除文件

编写AliOssConfig:

java">
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;}

具体实现类:

java">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 {@Autowiredprivate 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;}@Overridepublic 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;}
}

http://www.ppmy.cn/server/160592.html

相关文章

开发常用工具

在项目开发中&#xff0c;工具的使用起到了至关重要的作用&#xff0c;正所谓工欲善其事&#xff0c;必先利其器&#xff0c;掌握一些实用的开发工具能够使我们的开发效率事半功倍。 那么我们应该掌握哪些开发工具的使用方法呢&#xff1f;其实一路走来&#xff0c;我们已经介…

【Go】Go Gin框架初识(一)

1. 什么是Gin框架 Gin框架&#xff1a;是一个由 Golang 语言开发的 web 框架&#xff0c;能够极大提高开发 web 应用的效率&#xff01; 1.1 什么是web框架 web框架体系图&#xff08;前后端不分离&#xff09;如下图所示&#xff1a; 从上图中我们可以发现一个Web框架最重要…

Java-抽象方法

抽象方法&#xff1a; ●抽象方法&#xff1a;将共性的行为&#xff08;方法&#xff09;抽取到父类之后。由于每一个子类执行的内容是不一样&#xff0c;所以&#xff0c;在父类中不能确定具体的方法体。该方法就可以定义为抽象方法。 ●抽象类&#xff1a;如果一个类中存在…

[gpu驱动] H200 nvidia-fabricmanager-550升级到nvidia-fabricmanager-565报错,升级步骤

报错日志: root@h1-12-gpu:/home/canopy# apt install nvidia-fabricmanager-565 Reading package lists... Done Building dependency tree... Done Reading state information... Done Some packages could not be installed. This may mean that you have requested an imp…

【零基础入门unity游戏开发——unity通用篇36】向量(Vector3)的基本操作和运算(基于unity6开发介绍)

考虑到每个人基础可能不一样,且并不是所有人都有同时做2D、3D开发的需求,所以我把 【零基础入门unity游戏开发】 分为成了C#篇、unity通用篇、unity3D篇、unity2D篇。 【C#篇】:主要讲解C#的基础语法,包括变量、数据类型、运算符、流程控制、面向对象等,适合没有编程基础的…

feign调用跳过HTTPS的SSL证书校验配置详解

一、问题抛出 如果不配置跳过SSL证书校验&#xff0c;当Feign客户端尝试连接到一个使用自签名证书的服务器时&#xff0c;可能会抛出类似以下的异常&#xff1a; javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building faile…

【C++篇】红黑树封装 实现map和set

目录 前言&#xff1a; 一&#xff0c;库中map和set的大致结构 二&#xff0c;模拟实现 2.1&#xff0c;大致框架 2.2&#xff0c;复用红黑树实现insert接口 2.3&#xff0c;迭代器iterator的实现 operator()的实现&#xff1a; operator--()的实现&#xff1a; 对inser…

Docker导入镜像

使用命令行进行处理&#xff1a; docker load < onething1_wxedge.tar如下图所示 查看状态 docker images