文章目录
- 1. 开通对象存储服务
- 2. 创建 AccessKey 密钥
- 3. 通用代码实现
1. 开通对象存储服务
控制台 → 对象存储 OSS → 立即开通
Bucket列表 → 点击创建 Bucket
填写名称、地域,名称创建后不可修改,地域选择最近的,存储类型选择标准存储,读写权限选择公共读,其他地方默认。
2. 创建 AccessKey 密钥
点击 AccessKey 管理 → 创建 → 获得到的 Select 要保存好,自从今年七月后阿里云主账号就没有查看 Select 的功能了。
3. 通用代码实现
复制一下地域节点,一会会用到:
先在 pom 文件中引入依赖:
<dependencies>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.15.1</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>
</dependencies>
以下代码为固定格式,注意将字段信息换成自己的:
package com.zxe;
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 java.io.FileInputStream;
import java.io.InputStream;
public class Main {
public static void main(String[] args) throws Exception {
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "https://oss-cn-beijing.aliyuncs.com";
// 填写自己的id和密钥
String accessKeyId = "LTAI5t7hKVWEptz2i9HsHQn";
String accessKeySecret = "1AY9hSUot4KhZ8LGirsteBt5uea";
// 填写Bucket名称,例如examplebucket。
String bucketName = "andylau01";
// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
String objectName = "first.png";
// 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
// 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
String filePath= "C:\\Users\\Lenovo\\Desktop\\shitou.png";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream = new FileInputStream(filePath);
// 创建PutObjectRequest对象。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
// 创建PutObject请求。
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();
}
}
}
}
如图,我们的图片文件已经上传上去了:
把密钥直接写在代码里是不安全的,其实应该为 SDK 配置访问凭证,不对外公开 id 和 select,这样更安全。