首先要确定RAM访问控制的用户添加了oss权限
添加依赖
<dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.10.2</version></dependency>
service层代码
@Servicepublic class OssServiceImpl implements OssService {@Autowiredprivate OssProperties ossProperties;private String endpoint;private String accessKeyId;private String accessKeySecret;private String bucketName;@PostConstruct //java系统包自带的注解,标注的方法会在构造器调用完毕后执行一次public void init() {this.endpoint = this.ossProperties.getEndpoint();this.accessKeyId = this.ossProperties.getAccessKeyId();this.accessKeySecret = this.ossProperties.getAccessKeySecret();this.bucketName = this.ossProperties.getBucketName();}@Overridepublic String uploadImage(MultipartFile file) {try {// 创建OSSClient实例。OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);InputStream inputStream = file.getInputStream();// 依次填写Bucket名称(例如examplebucket)和Object完整路径(例如exampledir/exampleobject.txt)。Object完整路径中不能包含Bucket名称。String fileName = "headPortrait/" + new DateTime().toString("yyyy-MM-dd/")+ UUID.randomUUID().toString().replace("-", "")+ file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));// 参数1:保存文件的oss中的桶名; 参数2:保存上传的文件在桶内的路径和文件名; 参数3:上传的文件流ossClient.putObject(bucketName, fileName, inputStream);// 关闭OSSClient。ossClient.shutdown();// 这个图片路径需要手动拼接String path = "https://" + bucketName + ".oss-cn-/" + fileName;return path;} catch (Exception e) {// 将编译时的异常转为运行时的异常:异常抛出后会被全局异常处理器处理// throw new RuntimeException();// 抛出自定义异常throw new BusinessException("图片上传失败");}}}
OssProperties 类
@Data@Component@ConfigurationProperties(prefix = "aliyun.oss")public class OssProperties {String endpoint; //我们的桶存放的服务器地址String accessKeyId;String accessKeySecret;String bucketName;}
appliacation.yml文件中添加
aliyun:oss:endpoint: "https://oss-cn-" #以上海为例accessKeyId: "你的accessKeyId"accessKeySecret: "你的accessKeySecret"bucketName: "你的阿里云oss对象存储的bucket名称"
controller层代码
// 图片上传@PostMapping("uploadImage")public R uploadImage(MultipartFile file){// 注意前端上传的文件的表单项name值必须是fileString path = ossService.uploadImage(file);return R.ok(path);}