一、开通“对象存储OSS”服务
登录阿里云搜索oss服务,并开通
二. 使用RAM子用户
创建一个子用户用来管理
创建用户并设置权限
添加可操作的服务权限给创建的用户
创建Accesskey 需要在后面使用到
三 项目运用
使用SDK
四 项目创建
1.pom文件
<!-- https://mvnrepository.com/artifact/com.aliyun.oss/aliyun-sdk-oss -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
2.application.properties 配置文件
#阿里云oss存储系统
aliyun.oss.accessKeyId=“你的accesskeyId”
aliyun.oss.accessKeySecret="你的accessKeySecret"
aliyun.oss.endpoint=oss-cn-shanghai.aliyuncs.com
3.读取文件
@Data
@Component
@ConfigurationProperties(prefix = "aliyun.oss")
public class OssProperties implements InitializingBean {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
public static String ENDPOINT;
public static String KEY_ID;
public static String KEY_SECRET;
//当私有成员被赋值后,此方法自动被调用,从而初始化常量
@Override
public void afterPropertiesSet() throws Exception {
ENDPOINT = endpoint;
KEY_ID = accessKeyId;
KEY_SECRET = accessKeySecret;
}
}
4.代码编写测试
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import org.joda.time.DateTime;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import top.javahai.chatroom.config.OssProperties;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@RestController
@RequestMapping("file")
public class FileController {
@PostMapping("/file")
public String uploadFlie(@RequestParam("file") MultipartFile file,
@RequestParam("model")String model) throws IOException {
try {
InputStream inputStream = file.getInputStream();
String originalFilename = file.getOriginalFilename();
String url = upload(inputStream, model, originalFilename);
return url;
} catch (IOException e) {
System.out.println(e.getMessage());
return e.getMessage();
}
}
private String upload(InputStream inputStream,String model,String fileName){
//创建OssClient实例
OSS ossClient = new OSSClientBuilder().build(
OssProperties.ENDPOINT,
OssProperties.KEY_ID,
OssProperties.KEY_SECRET
);
//判断oss实例是否存在,如果不存在则创建,如果存在则获取
if(!ossClient.doesBucketExist(model)){
//创建bucket
ossClient.createBucket(model);
//设置oss实例的访问权限
ossClient.setBucketAcl(model, CannedAccessControlList.PublicRead);
}
//构建日期路径
String folder= new DateTime().toString("yyyy/MM/dd");
//文件名:uuid.扩展名
fileName=UUID.randomUUID().toString()+fileName.substring(fileName.lastIndexOf("."));
//文件的根路径
String key=model+"/"+folder+"/"+fileName;
//文件上传阿里云
ossClient.putObject(model,key,inputStream);
//
ossClient.shutdown();
return "https://"+model+"."+OssProperties.ENDPOINT+"/"+key;
}
结果;在这里会显示你所创建以及上传的文件