1,登录阿里云官网,开通oss对象存储
管理控制台是我已经开通过了,没有开始这里是立即开通,直接开通即可
2,点击管理控制台进入,创建Bucket(类似jav中的包)
3,创建阿里云的密码AccessKey ID 和 AccessKey Secret
并且记住AccessKey ID 和 AccessKey Secret,待会需要使用
4,查看阿里云oss文件上传的api
5,编写java接口代码
5.1阿里云对象存储-普通上传方式
这种方法浏览器需要把文件提交给服务器,服务器再把文件上传给OSS,每次上传都要经过微服务,太麻烦
5.1.1加入依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.15.1</version>
</dependency>
5.1.2配置文件
server.port=8002
spring.application.name=service-oss
spring.profiles.active=dev
//地域节点
aliyun.oss.file.endpoint=oss-cn-beijing.aliyuncs.com
aliyun.oss.file.keyid=LTAI4GD8gqB3npnPsc81vKXy
aliyun.oss.file.keysecret=gnh245WziZjzd8NG3nIi7CfQHcqlKG
aliyun.oss.file.bucketname=edu-20230220
5.1.3OssController
package com.atguigu.oss.controller;
import com.atguigu.commonutils.Result;
import com.atguigu.oss.service.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
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;
@RestController
@RequestMapping("/oss/file")
@Api(description="文件上传")
public class OssController {
@Autowired
private OssService ossService;
//上传头像的方法
@PostMapping
@ApiOperation(value = "上传头像")
public Result uploadOssFile(MultipartFile file) {
//获取上传文件 MultipartFile
//返回上传到oss的路径
String url = ossService.uploadFileAvatar(file);
return Result.ok().data("url",url);
}
}
5.1.4常量获取配置文件的值
package com.atguigu.oss.utils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//当项目已启动,spring接口,spring加载之后,执行接口一个方法
@Component
public class ConstantPropertiesUtils implements InitializingBean {
//读取配置文件内容
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;
@Value("${aliyun.oss.file.keyid}")
private String keyId;
@Value("${aliyun.oss.file.keysecret}")
private String keySecret;
@Value("${aliyun.oss.file.bucketname}")
private String bucketName;
//定义公开静态常量
public static String END_POIND;
public static String ACCESS_KEY_ID;
public static String ACCESS_KEY_SECRET;
public static String BUCKET_NAME;
@Override
public void afterPropertiesSet() throws Exception {
END_POIND = endpoint;
ACCESS_KEY_ID = keyId;
ACCESS_KEY_SECRET = keySecret;
BUCKET_NAME = bucketName;
}
}
5.1.5 OssService
package com.atguigu.oss.service;
import org.springframework.web.multipart.MultipartFile;
public interface OssService {
//上传头像到oss
String uploadFileAvatar(MultipartFile file);
}
5.1.6OssServiceImpl
package com.atguigu.oss.service.impl;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@Service
public class OssServiceImpl implements OssService {
//上传头像到oss
@Override
public String uploadFileAvatar(MultipartFile file) {
//工具类获取值
String endpoint = ConstantPropertiesUtils.END_POIND;
String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
try {
// 创建OSS实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//获取上传文件输入流
InputStream inputStream = file.getInputStream();
//获取文件名称
String fileName = file.getOriginalFilename();
//1 在文件名称里面添加随机唯一的值
String uuid = UUID.randomUUID().toString().replaceAll("-","");
//yuy76t5rew01.jpg
fileName = uuid+fileName;
//2 把文件按照日期进行分类
//获取当前日期
//2023/02/20
String datePath = new DateTime().toString("yyyy/MM/dd");
//拼接
//2023/02/20/ewtqr313401.jpg
fileName = datePath+"/"+fileName;
//调用oss方法实现上传
//第一个参数 Bucket名称
//第二个参数 上传到oss文件路径和文件名称 aa/bb/1.jpg
//第三个参数 上传文件输入流
ossClient.putObject(bucketName,fileName , inputStream);
// 关闭OSSClient。
ossClient.shutdown();
//把上传之后文件路径返回
//需要把上传到阿里云oss路径手动拼接出来
//https://edu-20230220.oss-cn-beijing.aliyuncs.com/01.jpg
String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
return url;
}catch(Exception e) {
e.printStackTrace();
return null;
}
}
}
5.1.7postman测试文件上传
注意:在文件名称加入了uuid是为了防止名称相同后面会覆盖前面的(不加上传相同的文件名称后面会覆盖前面的);uuid前面加入了时间格式,是为了用时间进行分组,在一个项目中会上传多个文件,这样可以根据上传时间分组
5.2阿里云对象存储-采用springclod-oss方式
5.2.1添加依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>aliyun-oss-spring-boot-starter</artifactId>
</dependency>
5.2.2添加配置文件
server:
port: 30000
spring:
cloud:
alicloud:
access-key: LTAI5tDj6DJJru2ajAtNZoxk
secret-key: EcGLQvQYyeRkJyZgvrIK6a1r7Eg6DW
oss:
endpoint: oss-cn-beijing.aliyuncs.com
bucket: gulimall-20240303
5.2.3使用SpringCloud阿里云封装好的OSSClient直接进行上传
测试用例
@SpringBootTest
public class TestFor {
@Resource
OSSClient ossClient;
@Test
public void test() throws FileNotFoundException {
FileInputStream inputStream = new FileInputStream("C:\\Users\\Pictures\\903d28ab0e2f4bb59bdf8f7c6fd22fe4.jpg");
ossClient.putObject("gulimall-xuda","903d28ab0e2f4bb59bdf8f7c6fd22fe4.jpg",inputStream);
ossClient.shutdown();
System.out.println("上传完成");
}
}
5.3阿里云对象存储-服务端签名后直传
这种方法浏览器可以直接把文件上传给文件存储为了安全,浏览器只需要找服务器要签名数据
5.3.1加入依赖
5.3.2配置文件
5.3.3获取签名数据
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Endpoint以华东1(杭州)为例,其他Region请按实际情况填写。
String endpoint = "oss-cn-hangzhou.aliyuncs.com";
// 填写Bucket名称,例如examplebucket。
String bucket = "examplebucket";
// 填写Host名称,格式为https://bucketname.endpoint。
String host = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com";
// 设置上传回调URL,即回调服务器地址,用于处理应用服务器与OSS之间的通信。OSS会在文件上传完成后,把文件上传信息通过此回调URL发送给应用服务器。
String callbackUrl = "https://192.168.0.0:8888";
// 设置上传到OSS文件的前缀,可置空此项。置空后,文件将上传至Bucket的根目录下。
String dir = "exampledir/";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
try {
long expireTime = 30;
long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
Date expiration = new Date(expireEndTime);
// PostObject请求最大可支持的文件大小为5 GB,即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
PolicyConditions policyConds = new PolicyConditions();
policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
byte[] binaryData = postPolicy.getBytes("utf-8");
String accessId = credentialsProvider.getCredentials().getAccessKeyId();
String encodedPolicy = BinaryUtil.toBase64String(binaryData);
String postSignature = ossClient.calculatePostSignature(postPolicy);
Map<String, String> respMap = new LinkedHashMap<String, String>();
respMap.put("accessid", accessId);
respMap.put("policy", encodedPolicy);
respMap.put("signature", postSignature);
respMap.put("dir", dir);
respMap.put("host", host);
respMap.put("expire", String.valueOf(expireEndTime / 1000));
// respMap.put("expire", formatISO8601Date(expiration));
JSONObject jasonCallback = new JSONObject();
jasonCallback.put("callbackUrl", callbackUrl);
jasonCallback.put("callbackBody",
"filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
respMap.put("callback", base64CallbackBody);
JSONObject ja1 = JSONObject.fromObject(respMap);
// System.out.println(ja1.toString());
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST");
response(request, response, ja1.toString());
} catch (Exception e) {
// Assert.fail(e.getMessage());
System.out.println(e.getMessage());
} finally {
ossClient.shutdown();
}
}