STS介绍
阿里云STS (Security Token Service) 是为阿里云账号(或RAM用户)提供短期访问权限管理的云服务。通过STS,您可以为联盟用户(您的本地账号系统所管理的用户)颁发一个自定义时效和访问权限的访问凭证。联盟用户可以使用STS短期访问凭证直接调用阿里云服务API,或登录阿里云管理控制台操作被授权访问的资源。
访问点
STS的默认访问点地址是: https://sts.aliyuncs.com
,用户必须使用https接入访问点。
术语表
术语 | 中文 | 说明 |
---|---|---|
Federated identity | 联盟用户身份 | 联盟用户的身份认证由客户自己管理 |
Policy | 访问策略 | 用来描述授权策略的一种描述语言 |
Grantor | 授权者 | 授权令牌的颁发者(云账号或RAM用户) |
Name | 被授权者 | 授权令牌的使用者(即联盟用户) |
https://help.aliyun.com/document_detail/28756.html?spm=a2c4g.11186623.2.9.4d4f412fzjwgui#reference-ong-5nv-xdb
授权访问
使用STS进行临时授权
OSS可以通过阿里云STS (Security Token Service) 进行临时授权访问。阿里云STS是为云计算用户提供临时访问令牌的Web服务。通过STS,您可以为第三方应用或子用户(即用户身份由您自己管理的用户)颁发一个自定义时效和权限的访问凭证。STS更详细的解释请参见STS介绍。
STS的优势如下:
- 您无需透露您的长期密钥(AccessKey)给第三方应用,只需生成一个访问令牌并将令牌交给第三方应用。您可以自定义这个令牌的访问权限及有效期限。
- 您无需关心权限撤销问题,访问令牌过期后自动失效。
使用STS访问OSS的流程请参见开发指南中的RAM和STS应用场景实践。
使用签名URL上传文件
以下代码用于使用签名URL上传文件:
// Endpoint以杭州为例,其它Region请按实际情况填写。
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
String bucketName = "<yourBucketName>";
String objectName = "<yourObjectName>"; // 创建OSSClient实例。
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); // 生成签名URL。
Date expiration = DateUtil.parseRfc822Date("Thu, 19 Mar 2019 18:00:00 GMT");
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.PUT);
// 设置过期时间。
request.setExpiration(expiration);
// 设置Content-Type。
request.setContentType("application/octet-stream");
// 添加用户自定义元信息。
request.addUserMetadata("author", "aliy");
// 生成签名URL(HTTP PUT请求)。
URL signedUrl = ossClient.generatePresignedUrl(request);
System.out.println("signed url for putObject: " + signedUrl); // 使用签名URL发送请求。
File f = new File("<yourLocalFile>");
FileInputStream fin = new FileInputStream(f);
// 添加PutObject请求头。
Map<String, String> customHeaders = new HashMap<String, String>();
customHeaders.put("Content-Type", "application/octet-stream");
customHeaders.put("x-oss-meta-author", "aliy");
PutObjectResult result = ossClient.putObject(signedUrl, fin, f.length(), customHeaders); // 关闭OSSClient。
ossClient.shutdown();
https://help.aliyun.com/document_detail/32016.html
错误码大全
https://error-center.aliyun.com/status/product/Oss
// endpoint以杭州为例,其它region请按实际情况填写
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// accessKey请登录https://ak-console.aliyun.com/#/查看
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
String content = "Hello OSS";
// 创建OSSClient实例
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
AppendObjectRequest appendObjectRequest = new AppendObjectRequest("<yourBucketName>",
"<yourKey>", new ByteArrayInputStream(content.getBytes()));
// 第一次追加
appendObjectRequest.setPosition(0L);
AppendObjectResult appendObjectResult = ossClient.appendObject(appendObjectRequest);
// 第二次追加
appendObjectRequest.setPosition(appendObjectResult.getNextPosition());
appendObjectResult = ossClient.appendObject(appendObjectRequest);
// 第三次追加
appendObjectRequest.setPosition(appendObjectResult.getNextPosition());
appendObjectResult = ossClient.appendObject(appendObjectRequest);
// 关闭client
ossClient.shutdown();
https://help.aliyun.com/document_detail/32013.html
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer; import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.AppendObjectRequest;
import com.aliyun.oss.model.AppendObjectResult;
import com.aliyun.oss.model.OSSObject; /**
* This sample demonstrates how to upload an object by append mode
* to Aliyun OSS using the OSS SDK for Java.
*/
public class AppendObjectSample { private static String endpoint = "*** Provide OSS endpoint ***";
private static String accessKeyId = "*** Provide your AccessKeyId ***";
private static String accessKeySecret = "*** Provide your AccessKeySecret ***"; private static String bucketName = "*** Provide bucket name ***";
private static String key = "*** Provide key ***"; public static void main(String[] args) throws IOException {
/*
* Constructs a client instance with your account for accessing OSS
*/
OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret); try {
/*
* Append an object from specfied input stream, keep in mind that
* position should be set to zero at first time.
*/
String content = "Thank you for using Aliyun Object Storage Service";
InputStream instream = new ByteArrayInputStream(content.getBytes());
Long firstPosition = 0L;
System.out.println("Begin to append object at position(" + firstPosition + ")");
AppendObjectResult appendObjectResult = client.appendObject(
new AppendObjectRequest(bucketName, key, instream).withPosition(0L));
System.out.println("\tNext position=" + appendObjectResult.getNextPosition() +
", CRC64=" + appendObjectResult.getObjectCRC() + "\n"); /*
* Continue to append the object from specfied file descriptor at last position
*/
Long nextPosition = appendObjectResult.getNextPosition();
System.out.println("Continue to append object at last position(" + nextPosition + "):");
appendObjectResult = client.appendObject(
new AppendObjectRequest(bucketName, key, createTempFile())
.withPosition(nextPosition));
System.out.println("\tNext position=" + appendObjectResult.getNextPosition() +
", CRC64=" + appendObjectResult.getObjectCRC()); /*
* View object type of the appendable object
*/
OSSObject object = client.getObject(bucketName, key);
System.out.println("\tObject type=" + object.getObjectMetadata().getObjectType() + "\n");
// Do not forget to close object input stream if not use it any more
object.getObjectContent().close(); /*
* Delete the appendable object
*/
System.out.println("Deleting an appendable object");
client.deleteObject(bucketName, key); } 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.getErrorCode());
System.out.println("Error Code: " + oe.getErrorCode());
System.out.println("Request ID: " + oe.getRequestId());
System.out.println("Host ID: " + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message: " + ce.getMessage());
} finally {
/*
* Do not forget to shut down the client finally to release all allocated resources.
*/
client.shutdown();
}
} private static File createTempFile() throws IOException {
File file = File.createTempFile("oss-java-sdk-", ".txt");
file.deleteOnExit(); Writer writer = new OutputStreamWriter(new FileOutputStream(file));
writer.write("abcdefghijklmnopqrstuvwxyz\n");
writer.write("0123456789011234567890\n");
writer.close(); return file;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/ package samples; import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer; import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest; /**
* This sample demonstrates how to upload/download an object to/from
* Aliyun OSS using the OSS SDK for Java.
*/
public class SimpleGetObjectSample { private static String endpoint = "*** Provide OSS endpoint ***";
private static String accessKeyId = "*** Provide your AccessKeyId ***";
private static String accessKeySecret = "*** Provide your AccessKeySecret ***"; private static String bucketName = "*** Provide bucket name ***";
private static String key = "*** Provide key ***"; public static void main(String[] args) throws IOException {
/*
* Constructs a client instance with your account for accessing OSS
*/
OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); try { /**
* Note that there are two ways of uploading an object to your bucket, the one
* by specifying an input stream as content source, the other by specifying a file.
*/ /*
* Upload an object to your bucket from an input stream
*/
System.out.println("Uploading a new object to OSS from an input stream\n");
String content = "Thank you for using Aliyun Object Storage Service";
client.putObject(bucketName, key, new ByteArrayInputStream(content.getBytes())); /*
* Upload an object to your bucket from a file
*/
System.out.println("Uploading a new object to OSS from a file\n");
client.putObject(new PutObjectRequest(bucketName, key, createSampleFile())); /*
* Download an object from your bucket
*/
System.out.println("Downloading an object");
OSSObject object = client.getObject(new GetObjectRequest(bucketName, key));
System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
displayTextInputStream(object.getObjectContent()); } 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.getErrorCode());
System.out.println("Error Code: " + oe.getErrorCode());
System.out.println("Request ID: " + oe.getRequestId());
System.out.println("Host ID: " + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message: " + ce.getMessage());
} finally {
/*
* Do not forget to shut down the client finally to release all allocated resources.
*/
client.shutdown();
}
} private static File createSampleFile() throws IOException {
File file = File.createTempFile("oss-java-sdk-", ".txt");
file.deleteOnExit(); Writer writer = new OutputStreamWriter(new FileOutputStream(file));
writer.write("abcdefghijklmnopqrstuvwxyz\n");
writer.write("0123456789011234567890\n");
writer.close(); return file;
} private static void displayTextInputStream(InputStream input) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
while (true) {
String line = reader.readLine();
if (line == null) break; System.out.println("\t" + line);
}
System.out.println(); reader.close();
} }
https://github.com/aliyun/aliyun-oss-java-sdk/blob/master/src/samples/SimpleGetObjectSample.java?spm=5176.12026607.tutorial.1.9c7732e2bQ2hBA&file=SimpleGetObjectSample.java
https://help.aliyun.com/document_detail/84781.html?spm=a2c4g.11186623.6.662.2cb51000luQAlv
https://segmentfault.com/a/1190000017273629?utm_source=tag-newest
在OSS控制台设置了CORS规则以后,通过JS程序去调用的时候报No ‘Access-Control-Allow-Origin’ header is present on the requested resource,可以通过下面的思路来进行下排查:
1. 确认检查CORS规则是否设置好了,是否设置正确,正确的设置方法如下图:
2. CORS设置都正确的话,那就检查AllowedHeader的设置,一般建议设置为*,设置方法如下:
https://help.aliyun.com/knowledge_detail/39518.html
参数 | 是否必须 | 说明 |
---|---|---|
来源 | 是 | 指定允许的跨域请求的来源。允许多条匹配规则,多条规则需换行填写。每条匹配规则允许使用最多一个星号(*)通配符。单独填写星号(*)通配符,表示允许所有来源的跨域请求。 |
允许 Methods | 是 | 指定允许的跨域请求方法。 |
允许 Headers | 否 | 指定允许的跨域请求的响应头。大小写不敏感,允许多条匹配规则,多条规则需换行填写。每条匹配规则最多使用一个星号(*)通配符。建议没有特殊需求的情况下设置为星号(*)。 |
暴露 Headers | 否 | 指定允许用户从应用程序中访问的响应头(例如,一个Javascript 的 XMLHttpRequest对象)。不允许使用星号(*)通配符。 |
缓存时间 | 否 | 指定浏览器对特定资源的预取(OPTIONS)请求返回结果的缓存时间。 |
设置跨域访问
跨域访问,或者说JavaScript的跨域访问问题,是浏览器出于安全考虑而设置的一个限制,即同源策略。当来自于A网站的页面中的JavaScript代码希望访问B网站的时候,浏览器会拒绝该访问,因为A、B两个网站是属于不同的域。
在实际应用中,经常会有跨域访问的需求,比如用户的网站www.a.com,后端使用了OSS。在网页中提供了使用JavaScript实现的上传功能,但是在该页面中,只能向www.a.com发送请求,向其他网站发送的请求都会被浏览器拒绝。这样就导致用户上传的数据必须从www.a.com中转。如果设置了跨域访问的话,用户就可以直接上传到OSS而无需从www.a.com中转。
跨域资源共享的实现
跨域资源共享(Cross-Origin Resource Sharing),简称CORS,是HTML5提供的标准跨域解决方案,OSS支持CORS标准来实现跨域访问。具体的CORS规则可以参考W3C CORS规范。其实现如下:
- CORS通过HTTP请求中附带Origin的Header来表明自己来源域,比如上面那个例子,Origin的Header就是www.a.com。
- 服务器端接收到这个请求之后,会根据一定的规则判断是否允许该来源域的请求。如果允许,服务器在返回的响应中会附带上Access-Control-Allow-Origin这个Header,内容为www.a.com来表示允许该次跨域访问。如果服务器允许所有的跨域请求,将Access-Control-Allow-Origin的Header设置为*即可。
- 浏览器根据是否返回了对应的Header来决定该跨域请求是否成功,如果没有附加对应的Header,浏览器将会拦截该请求。如果是非简单请求,浏览器会先发送一个OPTIONS请求来获取服务器的CORS配置,如果服务器不支持接下来的操作,浏览器也会拦截接下来的请求。
OSS提供了CORS规则的配置,从而根据需求允许或者拒绝相应的跨域请求。该规则是配置在Bucket级别的。详情可以参考PutBucketCORS。
细节分析
- CORS相关的Header附加等都是浏览器自动完成的,用户不需要有任何额外的操作。CORS操作也只在浏览器环境下有意义。
- CORS请求的通过与否和OSS的身份验证是完全独立的,即OSS的CORS规则仅仅是用来决定是否附加CORS相关的Header的一个规则。是否拦截该请求完全由浏览器决定。
- 使用跨域请求的时候需要关注浏览器是否开启了Cache功能。当运行在同一个浏览器上分别来源于www.a.com和www.b.com的两个页面都同时请求同一个跨域资源的时候,如果www.a.com的请求先到达服务器,服务器将资源带上Access-Control-Allow-Origin的Header为www.a.com返回给用户。这个时候www.b.com又发起了请求,浏览器会将Cache的上一次请求返回给用户,此时Header的内容和CORS的要求不匹配,就会导致后面的请求失败。
https://help.aliyun.com/document_detail/31870.html?spm=a2c4g.11186623.2.10.7ecc6a68CpGZAQ#concept-bwn-tjd-5db
本文介绍如何进行跨域资源共享。
跨域资源共享(Cross-origin resource sharing,简称CORS)允许Web端的应用程序访问不属于本域的资源。OSS提供跨域资源共享接口,方便您控制跨域访问的权限。
更多关于跨域资源共享的介绍,请参见开发指南中的设置跨域访问和API参考中PutBucketcors。
// Endpoint以杭州为例,其它Region请按实际情况填写。
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
String bucketName = "<yourBucketName>"; // 创建OSSClient实例。
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); SetBucketCORSRequest request = new SetBucketCORSRequest(bucketName); // 跨域资源共享规则的容器,每个存储空间最多允许10条规则。
ArrayList<CORSRule> putCorsRules = new ArrayList<CORSRule>(); CORSRule corRule = new CORSRule(); ArrayList<String> allowedOrigin = new ArrayList<String>();
// 指定允许跨域请求的来源。
allowedOrigin.add( "http://www.b.com"); ArrayList<String> allowedMethod = new ArrayList<String>();
// 指定允许的跨域请求方法(GET/PUT/DELETE/POST/HEAD)。
allowedMethod.add("GET"); ArrayList<String> allowedHeader = new ArrayList<String>();
// 是否允许预取指令(OPTIONS)中Access-Control-Request-Headers头中指定的Header。
allowedHeader.add("x-oss-test"); ArrayList<String> exposedHeader = new ArrayList<String>();
// 指定允许用户从应用程序中访问的响应头。
exposedHeader.add("x-oss-test1");
// AllowedOrigins和AllowedMethods最多支持一个星号(*)通配符。星号(*)表示允许所有的域来源或者操作。
corRule.setAllowedMethods(allowedMethod);
corRule.setAllowedOrigins(allowedOrigin);
// AllowedHeaders和ExposeHeaders不支持通配符。
corRule.setAllowedHeaders(allowedHeader);
corRule.setExposeHeaders(exposedHeader);
// 指定浏览器对特定资源的预取(OPTIONS)请求返回结果的缓存时间,单位为秒。
corRule.setMaxAgeSeconds(10); // 最多允许10条规则。
putCorsRules.add(corRule);
// 已存在的规则将被覆盖。
request.setCorsRules(putCorsRules);
ossClient.setBucketCORS(request); // 关闭OSSClient。
ossClient.shutdown();
https://help.aliyun.com/document_detail/32018.html?spm=a2c4g.11186623.6.690.676f2eaaWRN8fZ
获取跨域资源共享规则
以下代码用于获取跨域资源共享规则:
// Endpoint以杭州为例,其它Region请按实际情况填写。
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
String bucketName = "<yourBucketName>"; // 创建OSSClient实例。
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); ArrayList<CORSRule> corsRules;
// 获取跨域资源共享规则列表。
corsRules = (ArrayList<CORSRule>) ossClient.getBucketCORSRules(bucketName);
for (CORSRule rule : corsRules) {
for (String allowedOrigin1 : rule.getAllowedOrigins()) {
// 获取允许的跨域请求源。
System.out.println(allowedOrigin1);
} for (String allowedMethod1 : rule.getAllowedMethods()) {
// 获取允许的跨域请求方法。
System.out.println(allowedMethod1);
} if (rule.getAllowedHeaders().size() > 0){
for (String allowedHeader1 : rule.getAllowedHeaders()) {
// 获取允许的头部列表。
System.out.println(allowedHeader1);
}
} if (rule.getExposeHeaders().size() > 0) {
for (String exposeHeader : rule.getExposeHeaders()) {
// 获取允许的头部。
System.out.println(exposeHeader);
}
} if ( null != rule.getMaxAgeSeconds()) {
System.out.println(rule.getMaxAgeSeconds());
}
} // 关闭OSSClient。
ossClient.shutdown();
https://help.aliyun.com/document_detail/32018.html?spm=a2c4g.11186623.6.690.676f2eaaWRN8fZ
签名错误 (signature not match)
签名错误建议您排查以下问题:
参考在Header中包含签名中的签名方法以及示例,切记其中的\n是不能少的。
URL中出现特殊字符“+”等时,会有浏览器无法识别的情况,需要对签名做url coding,对“+”等做url编码,将+转换为“%2b”,浏览器才能识别。
使用如下的签名验证工具自行查看签名的过程,请您参考:https://bbs.aliyun.com/read/233851.html
推荐直接使用我们提供的SDK,这样避免您自己进行签名,我们帮您直接实现了签名的过程,请您参考:这里。
https://help.aliyun.com/knowledge_detail/66098.html?spm=a2c4g.11186631.2.8.6e892a8dwb2Hk5
java实现生成url签名的代码示例
生成签名以后的URL的示例代码如下:
// Generate a presigned URL Date expires = new Date (new Date().getTime() + 1000 * 60); // 1 minute to expire GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, key); generatePresignedUrlRequest.setExpiration(expires); URL url = client.generatePresignedUrl(generatePresignedUrlRequest); System.out.println(url.toString());
这段代码假定指定bucketName和key的Object已经上传到OSS,用户可以根据修改设定expires,即过期时间。更详细的操作可以参考OSSClient#generatePresignedUrl方法和GeneratePresignedUrlRequest类的帮助。
详细Java SDK文档可以参考:点击查看
https://help.aliyun.com/knowledge_list/51639.html?spm=a2c4g.11186623.3.3.697c7681h465JK
@Slf4j
@Service
public class AliOSSServiceImpl implements OSSService { @Autowired
private OssConfig ossConfig; @Override
public UploadOSSVO generatePresignedUrl(UploadOSSReq req) {
String bucketName = ossConfig.getBucket();
OSSClient ossClient = null;
try {
ossClient = getOssClient();
// 设置文件路径和名称
// https://filetest.gongbangbang.com/resources/u/2019/02/11/ea05ef6c4fce4e04a910fb38a2643a1fBJxmpf.jpg
String key = getObjectName(req);
// 创建请求。
GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, key);
// HttpMethod为PUT。
generatePresignedUrlRequest.setMethod(HttpMethod.PUT);//要使用put方法进行上传
// // 添加用户自定义元信息。
generatePresignedUrlRequest.addUserMetadata("author", "jackie");
// 添加Content-Type。
generatePresignedUrlRequest.setContentType("application/octet-stream");//要指定HttpHeader
// 设置URL过期时间为1小时。
generatePresignedUrlRequest.setExpiration(LocalDateTime.now().plusHours(1).toDate());
// 上传文件
URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
String query = url.getQuery();
return new UploadOSSVO(ossConfig.getOssResourceUrl(key) + "?" + query);
} catch (OSSException oe) {
log.error("生成url失败 OSSException {}", oe.getMessage(), oe);
throw oe;
} catch (ClientException ce) {
log.error("生成url失败 ClientException {}", ce.getErrorMessage());
throw ce;
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
} /**
* 上传文件。
*
* @param file 需要上传的文件路径
* @return 如果上传的文件是图片的话,会返回图片的"URL",如果非图片的话会返回"非图片,不可预览。文件路径为:+文件路径"
*/
@Override
public String upLoad(File file) throws IOException {
log.info("------OSS文件上传开始--------{}", file.getName());
Assert.notNull(file, "往ali oss 上传的文件为空");
Assert.isTrue(file.exists(), "往ali oss上传的文件不存在");
String bucketName = ossConfig.getBucket();
OSSClient ossClient = null;
try {
ossClient = getOssClient();
// 设置文件路径和名称
// https://filetest.gongbangbang.com/resources/u/2019/02/11/ea05ef6c4fce4e04a910fb38a2643a1fBJxmpf.jpg
String key = getObjectName(new UploadOSSReq(FilenameUtils.getExtension(file.getName())));
// 上传文件
PutObjectResult putObjectResult = ossClient.putObject(bucketName, key, file);
String ossResourceUrl = ossConfig.getOssResourceUrl(key);
if (putObjectResult != null) {
log.info("PutObjectResult:{}", JSON.toJSONString(putObjectResult));
// 设置权限(公开读)
ossClient.setObjectAcl(bucketName, key, CannedAccessControlList.PublicRead);
log.info("------OSS文件上传成功------ {}", ossResourceUrl);
FileUtils.deleteQuietly(file);
return ossResourceUrl;
}
log.warn("OSS文件上传失败。 putObjectResult is null");
throw new IOException("OSS文件上传失败。putObjectResult is null");
} catch (OSSException oe) {
log.error(oe.getMessage(), oe);
throw oe;
} catch (ClientException ce) {
log.error(ce.getErrorMessage(), ce);
throw ce;
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
} /**
* 上传的资源在OSS上的路径
*
* @param req
* @return
*/
private String getObjectName(UploadOSSReq req) {
return ossConfig.getPath() + LocalDate.now().toString("yyyy/MM/dd") + "/" + RandomUtils.getRandomFileName() + req.getSuffix();
} /**
* 初始化OSS Client对象
*
* @return
*/
private OSSClient getOssClient() {
OSSClient ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessId(), ossConfig.getAccessKey());
// 判断容器是否存在,不存在就创建
String bucketName = ossConfig.getBucket();
if (!ossClient.doesBucketExist(bucketName)) {
ossClient.createBucket(bucketName);
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
ossClient.createBucket(createBucketRequest);
}
return ossClient;
}
}