阿里云对象存储OSS服务——上传/删除/获取图片
1. 准备工作
- 开通对象存储 OSS服务
- 创建AccessKey(使用阿里云OSS SDK时需要使用到)
- 创建Bucket(输入唯一的Bucket名字,选择合适的区域,其他选项默认)
- 创建Spring Boot项目
- 推荐使用Postman测试后端API,Postman的下载及使用参考 https://blog.youkuaiyun.com/fxbin123/article/details/80428216
- 注意:使用Postman测试上传图片功能时,需要将请求体(Body)的类型设为form-data
2. 上传图片
// 未对异常进行处理
@PostMapping(value = "/image")
public void uploadImage(MultipartFile file) {
// MultipartFile代表HTML中form data方式上传的文件
// EndPoint以上海为例
String endPoint = "oss-cn-shanghai.aliyuncs.com";
// 阿里云API秘钥
String accessKeyId = "<your access key id>";
String accessKeySecret = "<your access key secret>";
String bucketName = "<bucket name>";
OSSClient client = new OSSClient(endPoint, accessKeyId, accessKeySecret);
client.putObject(bucketName, imageName, new ByteArrayInputStream(file.getBytes()));
client.shutdown