前言
接入oss必须有这两个文档基础
使用STS临时访问凭证访问OSS_对象存储(OSS)-阿里云帮助中心
前端上传跨域
正文
sts前后端通用,开通图示
AliyunSTSAssumeRoleAccess
后端实现代码
public static void main(String[] args) {
String regionId = "cn-hangzhou";
String endpoint = "sts.cn-hangzhou.aliyuncs.com";
String accessKeyId = "accessKeyId"; //用户提供
String accessKeySecret = "accessKeySecret";//用户提供
String roleArn = "acs:ram::roleArn:role/ramoss";//角色提供
String roleSessionName = "roleSessionName";// 自定义
String bucket = "bucket"; // 对应创建buket 前端上传记得开跨域
String policy = "{\n" +
" \"Version\": \"1\", \n" +
" \"Statement\": [\n" +
" {\n" +
" \"Action\": [\n" +
" \"oss:PutObject\"\n" +
" ], \n" +
" \"Resource\": [\n" +
" \"acs:oss:*:*:sc-sale-servcie/test/*\" \n" +
" ], \n" +
" \"Effect\": \"Allow\"\n" +
" }\n" +
" ]\n" +
"}";
Long durationSeconds = 3600L;
try {
DefaultProfile.addEndpoint("", regionId, "Sts", endpoint);
IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
// 构造client。
DefaultAcsClient client = new DefaultAcsClient(profile);
final AssumeRoleRequest request = new AssumeRoleRequest();
request.setMethod(MethodType.POST);
request.setRoleArn(roleArn);
request.setRoleSessionName(roleSessionName);
//request.setPolicy(policy);
request.setDurationSeconds(durationSeconds);
// 如果前端上传这个给前端 把跨域打开
final AssumeRoleResponse response = client.getAcsResponse(request);
System.out.println("Expiration: " + response.getCredentials().getExpiration());
System.out.println("Access Key Id: " + response.getCredentials().getAccessKeyId());
System.out.println("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
System.out.println("Security Token: " + response.getCredentials().getSecurityToken());
System.out.println("RequestId: " + response.getRequestId());
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build("https://oss-cn-hangzhou.aliyuncs.com", response.getCredentials().getAccessKeyId(), response.getCredentials().getAccessKeySecret(), response.getCredentials().getSecurityToken());
PutObjectRequest putObjectRequest = new PutObjectRequest("reformer", "1/reformer.sql", new File("/Users/xushouchun/IdeaProjects/REformer-boot/fromer-start/src/main/resources/database/reformer.sql"));
try {
// 上传文件。
PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
System.out.println("putObjectResult = " + JSON.toJSONString(putObjectResult));
// copy
CopyObjectRequest copyObjectRequest = new CopyObjectRequest(bucket, "1/reformer.sql", bucket, "1/sql.reformer");
ossClient.copyObject(copyObjectRequest);
// 生成下载URL
Date expirationDate = new Date(new Date().getTime() + durationSeconds); // URL 的有效期
GeneratePresignedUrlRequest requests = new GeneratePresignedUrlRequest(bucket, "1/reformer.sql");
requests.setExpiration(expirationDate);
ossClient.generatePresignedUrl(requests);
} 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());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
} catch (ClientException e) {
System.out.println("Failed:");
System.out.println("Error code: " + e.getErrCode());
System.out.println("Error message: " + e.getErrMsg());
System.out.println("RequestId: " + e.getRequestId());
}
}
工具
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ResponseHeaderOverrides;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author :
* Author: 徐寿春
* Date: 2024/4/28 15:04
* <p>
* 名称
*/
@Component
@Slf4j
public class OSSUtils {
@Value("${oss.accessKey}")
String accessKey;
@Value("${oss.secretKey}")
String secretKey;
@Value("${oss.sts_endpoint}")
String stsEndPoint;
@Value("${oss.endpoint}")
String endpoint;
@Value("${oss.arn}")
String arn;
@Value("${oss.bucket}")
String bucket;
@Value("${oss.roleSessionName}")
String roleSessionName;
//一天
static Long durationSeconds = (long) 24 * 60 * 60 * 1000;
public AssumeRoleResponse buildAliyunSTSCredentials() throws ClientException {
// STS
DefaultProfile.addEndpoint(stsEndPoint, "cn-hangzhou", "Sts", "sts.cn-hangzhou.aliyuncs.com");
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKey, secretKey);
DefaultAcsClient client = new DefaultAcsClient(profile);
final AssumeRoleRequest request = new AssumeRoleRequest();
request.setMethod(MethodType.POST);
request.setProtocol(ProtocolType.HTTPS);
// sts 时间
request.setDurationSeconds(durationSeconds);
request.setRoleArn(arn); // 要扮演的角色ID
request.setRoleSessionName(roleSessionName);
// 生成临时授权凭证
return client.getAcsResponse(request);
}
public List<String> listOss(String directory) {
ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucket).withPrefix(directory).withMaxKeys(1000);
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, secretKey);
ObjectListing objectListing = ossClient.listObjects(listObjectsRequest);
return objectListing.getObjectSummaries().stream().map(OSSObjectSummary::getKey).filter(key -> !key.equals(directory + File.separator)).collect(Collectors.toList());
}
/**
* oss文件拷贝
*
* @param sourceObjectName "your/source/object/name";
* @param destinationObjectName "your/destination/object/name";
*/
public void ossCopyObject(String sourceObjectName, String destinationObjectName) {
log.info("ossCope, {} -> {}", sourceObjectName, destinationObjectName);
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, secretKey);
try {
ossClient.copyObject(bucket, sourceObjectName, bucket, destinationObjectName);
} catch (Exception e) {
e.printStackTrace();
} finally {
ossClient.shutdown();
}
}
/**
* oss文件上传
*
* @param path "your/source/object/name";
* @param input "io";
*/
public void ossPutObject(String path, InputStream input) {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, secretKey);
try {
ossClient.putObject(bucket, path, input);
} catch (Exception e) {
e.printStackTrace();
} finally {
ossClient.shutdown();
}
}
/**
* 生成一个下载URL
*
* @param objectName "your/destination/object/name";
* @return
*/
public URL generatePresignedUrl(String objectName) {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey, secretKey);
Date expirationDate = new Date(new Date().getTime() + durationSeconds); // URL 的有效期
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucket, objectName);
//设置响应头强制下载
ResponseHeaderOverrides responseHeaders = new ResponseHeaderOverrides();
responseHeaders.setContentDisposition("attachment;");
request.setResponseHeaders(responseHeaders);
request.setExpiration(expirationDate);
URL url = ossClient.generatePresignedUrl(request);
ossClient.shutdown();
// 生成URL
return url;
}
}
总结
后端代码已经提供,前端就比较简单了,拿到钥匙直接upload就可以了。 一般脚手架都有,凭借url即可
前端文档: sts前端上传代码