当前位置:网站首页>阿里云OSS文件上传
阿里云OSS文件上传
2022-08-10 00:59:00 【JagTom】
需求分析:实现文件上传与下载 ,与SprinCloud Alibaba整合
步骤一:注册帐号

第二步:创建Bucket

第三步,创建Accesskey
注意:创建时候一定记得复制帐号密码,密码只在创建成功后显示一次!

第四步:安装对象存储OSS并使用
官方是原生的使用方法,导入原生包
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.15.0</version>
</dependency>@Test
public void SossTest() throws FileNotFoundException {
// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
String endpoint = "oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = "LTAI5t7Mo77o7AMrp******";
String accessKeySecret = "qpXXnqaRegprSzYn******";
// 填写Bucket名称,例如examplebucket。
String bucketName = "gilgamesh-mail";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
InputStream inputStream=new FileInputStream("文件路径.jpg");
// 创建存储空间。
ossClient.putObject(bucketName,"上传的文件取个名字",inputStream);
// 关闭OSSClient。
ossClient.shutdown();
System.out.println("ok");
}使用方法二:SpringCloud alibaba-oss
导入依赖
<!-- 文件上传与下载 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alicloud-oss</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>配置application.yaml
# mysql
spring:
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
alicloud:
access-key: LTAI5t7Mo77o****** #阿里oss文件上传与下载
secret-key: qpXXnqaRegprSzYn45QJ9XsWRtW4tk*****
endpoint: oss-cn-hangzhou.aliyuncs.com
application:
name: ThirdPartModle编写Controller
@RestController
public class OssController {
@Resource
OSSClient ossClient;
@Value("${spring.cloud.alicloud.oss.endpoint}")
private String endpoint;
@Value("${spring.cloud.alicloud.access-key}")
private String accessId;
@RequestMapping("/oss/policy")
public R policy(){
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
// String accessId = "yourAccessKeyId";
// String accessKey = "yourAccessKeySecret";
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
// String endpoint = "oss-cn-hangzhou.aliyuncs.com";
// 填写Bucket名称,例如examplebucket。
String bucket = "gilgamesh-mail";
// 填写Host地址,格式为https://bucketname.endpoint。
String host = "https://"+bucket+"."+endpoint;
// 设置上传回调URL,即回调服务器地址,用于处理应用服务器与OSS之间的通信。OSS会在文件上传完成后,把文件上传信息通过此回调URL发送给应用服务器。
// String callbackUrl = "https://192.168.0.0:8888";
// 设置上传到OSS文件的前缀,可置空此项。置空后,文件将上传至Bucket的根目录下。
String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String dir = format+"/";
Map<String, String> respMap=null;
// OSSClient client = new OSSClient(endpoint, accessId, accessKey);
try {
long expireTime = 30;
long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
Date expiration = new Date(expireEndTime);
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 encodedPolicy = BinaryUtil.toBase64String(binaryData);
String postSignature =ossClient.calculatePostSignature(postPolicy);
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());
}
return R.ok().put("data",respMap);
}
}cors跨域问题:

边栏推荐
- Teach you how to write performance test cases
- 开发IM即时通讯容易吗?需要什么技术
- Unity editor extension interface uses List
- JVM :运行时数据区-虚拟机栈
- Penetration Testing and Offensive and Defense Confrontation - Vulnerability Scanning & Logic Vulnerability (Part1)
- 头脑风暴:单词拆分
- GB28181 sip和RTSP(Real-Time Streaming Protocol)实时流控制协议
- Web性能测试模型小结
- JDBC数据库连接池练习题
- 什么是持续测试?
猜你喜欢

Xi'an biotin-tetrapolyethylene glycol-amide-4phenol light yellow semi-solid

Sikuli's Automated Testing Technology Based on Pattern Recognition

罗彻斯特大学 | 现在是什么序列?蛋白质序列的贝叶斯优化的预训练集成

C language structure, function and pointer exercise (simple address book)

鲜花线上销售管理系统的设计与实现
![[论文阅读] Diverse Image-to-Image Translation via Disentangled Representations](/img/b8/891b8a8e7e70a1abd2016337ebc744.jpg)
[论文阅读] Diverse Image-to-Image Translation via Disentangled Representations

Unity reports Unsafe code may only appear if compiling with /unsafe. Enable “Allow ‘unsafe’ code” in Pla

卷积神经网络识别验证码

How to add control panel to right click menu in win7

XSS高级 svg 复现一个循环问题以及两个循环问题
随机推荐
03|Process Control
Solve the problem of sed replacement text containing special characters such as "/" and "#"
-red and black-
彩色袜子题
【UNR #6 C】稳健型选手(分治)(主席树)(二分)
使用 apxs 构建和安装 Apache 扩展共享对象模块
How to add control panel to right click menu in win7
ABAP 里文件操作涉及到中文字符集的问题和解决方案
【Grpc】简介
JDBC数据库连接池练习题
[转] Typora_Markdown_图片标题(题注)
Biotin-Cy2 Conjugate, Biotin-Cy2 Conjugate_Cy2 Biotin Conjugate
unity编辑器扩展界面使用 List
改变社交与工作状态的即时通讯是什么呢?
hint: Updates were rejected because the tip of your current branch is behind hint: its remote counte
Shader Graph学习各种特效案例
万字总结:分布式系统的38个知识点
浏览器中的history详解
mstsc/Mstsc (Microsoft terminal services client)远程桌面连接
【kali-密码攻击】(5.1.2)密码在线破解:Medusa