文章目录
- 开通对象存储服务
- 密钥管理
- 点击头像点击密钥管理
- 创建新密钥AccessKey
- 写在yml配置文件中
- 相关配置
- 1.pom依赖
- 2.全局配置类
- 3.AliOssUtil 工具类
- 3.AliOssProperties类,用于读取yml文件中写入的密钥
- 4.controller层,用于写传输文件的接口
开通对象存储服务
在对象存储oss创建Bucket列表,详细流程去网上可以看教程。
密钥管理
点击头像点击密钥管理
创建新密钥AccessKey
验证后会给你一个AccessKey ID和AccessKey Secret,把他复制好记录在记事本上。
写在yml配置文件中
#阿里云oss配置
alioss:endpoint: oss-cn-shanghai.aliyuncs.comaccess-key-id: LTAI5tKXTEM5sNWAMd5H2j5LGzaccess-key-secret: TDSTJK2SJ7UGyepbruIxEXWZ2LZsq8T7bucket-name: lonelykky
在这里写你刚刚复制的id和secret
相关配置
1.pom依赖
导入阿里云相关依赖
<!--阿里云OSS--><dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.10.2</version></dependency><dependency><groupId>javax.xml.bind</groupId><artifactId>jaxb-api</artifactId><version>2.3.1</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency>
2.全局配置类
写入OssConfiguration 创建oss对象
@Configuration
@Slf4j
public class OssConfiguration {@Beanpublic AliOssUtil aliOssUtil(AliOssProperties aliOssProperties) {log.info("开始创建阿里云文件oss对象");return new AliOssUtil(aliOssProperties.getEndpoint(),aliOssProperties.getAccessKeyId(),aliOssProperties.getAccessKeySecret(),aliOssProperties.getBucketName());}
}
3.AliOssUtil 工具类
@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/ObjectNameStringBuilder stringBuilder = new StringBuilder("https://");stringBuilder.append(bucketName).append(".").append(endpoint).append("/").append(objectName);log.info("文件上传到:{}", stringBuilder.toString());return stringBuilder.toString();}
}
3.AliOssProperties类,用于读取yml文件中写入的密钥
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;@Component
@ConfigurationProperties(prefix = "alioss")
@Data
public class AliOssProperties {private String endpoint;private String accessKeyId;private String accessKeySecret;private String bucketName;}
4.controller层,用于写传输文件的接口
package com.kkk.controller;import com.kkk.common.utils.AliOssUtil;
import com.kkk.common.utils.Result;
import com.kkk.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import java.io.IOException;
import java.util.UUID;/*** 文件上传* @author lonelykkk* @email 2765314967@qq.com* @date 2024/5/15 9:12* @Version V1.0*/
@RestController
@Slf4j
public class UploadController {@Autowiredprivate AliOssUtil aliOssUtil;@PostMapping("/upload")public Result upload(MultipartFile img) {log.info("file:{}", img);try {//原始文件名String originalFilename = img.getOriginalFilename();//截取原始文件名的后缀 dfdfdf.pngString extension = originalFilename.substring(originalFilename.lastIndexOf("."));//构造新文件名称String objectName = UUID.randomUUID().toString() + extension;//文件的请求路径String filePath = aliOssUtil.upload(img.getBytes(), objectName);return Result.okResult(filePath);} catch (IOException e) {log.error("文件上传失败:{}", e);}return Result.errorResult(507, "文件上传失败");}
}
接下来就可以根据请求路径上传文件了。