文章目录
- 准备阿里云的OSS
- 控制台
- 创建bucket
- 获取AccessKey
- java使用oss
- 导入依赖
- 官网demo
- 修改参数
- 运行demo代码
- 封装工具类
- Oss下载
- 如何保证指定时间段内可以访问私有权限的图片文件?
准备阿里云的OSS
控制台
访问阿里云官网,登录以后,右上角有个控制台
点击左上角,然后搜索oss
因为我没有开通过,所以提示开通
点击开通
创建bucket
填写bucket名称和选择读写权限为公共读,然后完成创建
然后bucket列表中,就有刚才创建的bucket了
点击列表中的bucket名称,然后点击概览,看到一些基础信息,其中有个Endpoint,上传文件会用到
获取AccessKey
鼠标移到右上角头像处,有个AccessKey管理,点击来获取AccessKey,
选择继续使用
然后点击创建AccessKey,再验证手机验证码,就成功创建,需要注意的是,获取到AccessKey以后,要保存好,关闭这个窗口就看不到了
java使用oss
左边最下面有个sdk下载
java后面有个小图标,点一下
文档中心打开
导入依赖
左边找到java-安装,我是maven项目,选择导入pom依赖,,它有说明,java9以上要引入下面那部分,具体看你版本,我是9以上,两部分依赖都要
<!--oss依赖-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.17.4</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<!-- no more than 2.3.3-->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.3</version>
</dependency>
官网demo
依赖有了,现在要做的就是上传文件的测试demo了,找到测试demo,粘到项目代码中
修改参数
粘贴过来以后,把一些关键参数换成我们实际的数值
demo需要修改的参数说明
运行demo代码
package com.wzw.alioss;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
public class DemoTest {
public static void main(String[] args) throws Exception {
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "https://oss-cn-beijing.aliyuncs.com";
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
//EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
String ACCESS_KEY_ID = "LTAI5tRHMRGaK14mSm1LNRkB";
String ACCESS_KEY_SECRET = "mrniIO007QfxpdsMzW0CDROcPjoTfg";
// 填写Bucket名称,例如examplebucket。
String bucketName = "ali-bucket-space";
// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
String objectName = "dog.jpg";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, ACCESS_KEY_ID,ACCESS_KEY_SECRET);
try {
// 创建PutObjectRequest对象。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new FileInputStream("C:\\Users\\w4523\\Desktop\\dogjpg.jpg"));
// 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);
// 上传字符串。
PutObjectResult result = ossClient.putObject(putObjectRequest);
} 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());
} 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 {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
运行,上传成功
封装工具类
上面参数说明已经看到了,其实很多东西都是固定的,只有一些值需要传入就可以了,现在封装成一个工具类,只传入我们要上传的文件对象就可以了
package com.wzw.alioss.com.wzw.alioss.util;
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.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.InputStream;
public class AliOssUtil {
//地域节点
private static final String endpoint="https://oss-cn-beijing.aliyuncs.com";
//ACCESS_KEY_ID
private static final String ACCESS_KEY_ID="LTAI5tRHMRGaK14mSm1LNRkB";
//ACCESS_KEY_SECRET
private static final String ACCESS_KEY_SECRET="mrniIO007QfxpdsMzW0CDROcPjoTfg";
//bucket名称
private static final String bucketName="ali-bucket-space";
/**
* 上传文件到OSS
* @param objectName
* @param inputStream
* @return
* @throws Exception
*/
public static String uploadFile(String objectName, InputStream inputStream) throws Exception {
//文件存储的地址
String url="";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, ACCESS_KEY_ID,ACCESS_KEY_SECRET);
try {
// 创建PutObjectRequest对象。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
// 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);
// 上传字符串。
PutObjectResult result = ossClient.putObject(putObjectRequest);
/**
* 示例中上传的文件地址:https://ali-bucket-space.oss-cn-beijing.aliyuncs.com/dog.jpg
* 根据这个地址url可以观察到,它是https://+bucketName+区域节点+objectName
*/
url="https://"+bucketName+"."+endpoint.substring(endpoint.lastIndexOf("/")+1)+"/"+objectName;
} 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());
} 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 {
if (ossClient != null) {
ossClient.shutdown();
}
}
return url;
}
}
controller调用
package com.wzw.alioss.com.wzw.alioss.controller;
import com.wzw.alioss.com.wzw.alioss.util.AliOssUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.UUID;
@RestController
public class AliOssController {
/**
* 上传文件到OSS
* @param file
* @return
* @throws IOException
*/
@PostMapping("/upload")
public String uploadFile(MultipartFile file) throws Exception {
String fileName=file.getOriginalFilename();
String url = AliOssUtil.uploadFile(UUID.randomUUID()+fileName.substring(fileName.lastIndexOf(".")), file.getInputStream());
return url;
}
}
发送postman请求,看到结果也返回了url
查看bucket,上传成功
整个示例代码:https://gitee.com/w452339689/alioss_test
Oss下载
如果是公开的,直接访问固定的url就行,如果是私有的,需要授权
如何保证指定时间段内可以访问私有权限的图片文件?
访问私有云文件url提示如下
私有云访问也是需要认证的,可以通过文件名授权一个临时的url,在指定的时间内可以访问。
官方文档:https://help.aliyun.com/zh/oss/user-guide/how-to-access-a-private-image-object-within-a-specific-period-of-time?spm=a2c4g.11186623.0.i20
成功获取,查看能不能访问到,完成
封装工具类
/**
* 阿里云oss生成临时访问路径
* @param objectName 文件名631ffc15-83d8-478f-95e5-5a8a96afa7d4.png
*/
public static String getOssUrl(String objectName) {
String fileUrl="";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, ACCESS_KEY_ID,ACCESS_KEY_SECRET);
try {
// 设置签名URL过期时间为1天,单位为秒,
Date expiration = new Date(new Date().getTime() + 3600 * 1000);
// 生成以GET方法访问的签名URL,在签名URL有效期内访客可以直接通过浏览器访问相关内容。
URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
System.out.println(url.toString());
if(Optional.ofNullable(url).isPresent()) {
return fileUrl=url.toString();
}
} catch (OSSException oe) {
log.error("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
log.error("Error Message:" + oe.getErrorMessage());
log.error("Error Code:" + oe.getErrorCode());
log.error("Request ID:" + oe.getRequestId());
log.error("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
log.error("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.");
log.error("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return fileUrl;
}
可能遇到一个问题,访问临时url,提示如下,看信息应该是时间不对,我之前设置的是30天,调整成1天就好了。