OSS文件上传
1.在application.yml核心配置文件中添加
spring: profiles: active: dev sky: alioss: endpoint: ${sky.alioss.endpoint} access-key-id: ${sky.alioss.access-key-id} access-key-secret: ${sky.alioss.access-key-secret} bucket-name: ${sky.alioss.bucket-name}
2.在application-dev.yml开发者配置文件中添加
# 阿里云OSS alioss: endpoint: oss-accelerate.aliyuncs.com # oss全球加速域名 bucket-name: tangguangyu # 存储空间名称 access-key-id: LTAI5tSp9arZfkrg6dnyv9Hw # 访问密钥ID access-key-secret: 5guoa94EJ8788ld7W5TQSMJYXNYFA1 # 访问密钥Secret
3.创建AliOssProperties 用于读取配置
package com.sky.properties; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "sky.alioss")// 绑定配置文件中的sky.alioss.* @Data public class AliOssProperties { private String endpoint; private String accessKeyId; private String accessKeySecret; private String bucketName; }
4.将 AliOssProperties 读取并注入到spring容器之中
package com.sky.config; import com.sky.properties.AliOssProperties; import com.sky.utils.AliOssUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * 阿里云文件上传配置 * 用于创建 AliOssUtil 对象 */ @Configuration @Slf4j public class OssConfiguration { @Bean @ConditionalOnMissingBean //当容器中没有这个bean对象时,才创建这个对象 public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties){ log.info("开始创建阿里云文件上传工具类对象:{}",aliOssProperties); return new AliOssUtil( aliOssProperties.getEndpoint(), aliOssProperties.getAccessKeyId(), aliOssProperties.getAccessKeySecret(), aliOssProperties.getBucketName()); } }
5.创建阿里云工具类用于上传文件并返回文件名称
package com.sky.utils; import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import lombok.AllArgsConstructor; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import java.io.ByteArrayInputStream; @Data @AllArgsConstructor @Slf4j public class AliOssUtil { private String endpoint; private String accessKeyId; private String accessKeySecret; private String bucketName; /** * 文件上传 * * @param bytes * @param objectName * @return */ public String upload(byte[] bytes, String objectName) { // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); try { // 创建PutObject请求。 ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes)); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("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."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } //文件访问路径规则 https://BucketName.Endpoint/ObjectName StringBuilder stringBuilder = new StringBuilder("https://"); stringBuilder .append(bucketName) .append(".") .append(endpoint) .append("/") .append(objectName); log.info("文件上传到:{}", stringBuilder.toString()); return stringBuilder.toString(); } }
6.使用上传
@Autowired private AliOssUtil aliOssUtil; @PostMapping("/upload") @ApiOperation("文件上传") public Result<String> upload(MultipartFile file) { log.info("文件上传:{}", file); try { //原始文件名 String originalFilename = file.getOriginalFilename(); log.info("原始文件名:{}", originalFilename); //截取原文件名称 String extension = originalFilename.substring(originalFilename.lastIndexOf(".")); log.info("原文件名称:{}", extension); //生成UUID为新文件名称 String objectName = UUID.randomUUID().toString() + extension; //上传到阿里云并返回文件访问路径 String fullPath = aliOssUtil.upload(file.getBytes(), objectName); return Result.success(fullPath); } catch (IOException e) { log.error("文件上传失败:{}", e); } return Result.error("上传失败"); }
原文地址:https://blog.csdn.net/a1241436267/article/details/143726894
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!