当前位置:网站首页>阿里云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跨域问题:

边栏推荐
- 什么是一网统管?终于有人讲明白了
- Entity FrameWork Core教程,从基础应用到原理实战
- 【kali-密码攻击】(5.1.2)密码在线破解:Medusa
- 基于Web的疫情隔离区订餐系统
- [论文阅读] Multimodal Unsupervised Image-to-Image Translation
- R语言使用glm函数构建logistic回归模型,使用forestmodel包的forest_model函数可视化逻辑回归模型对应的森林图
- 【软考软件评测师】软件测试基础知识
- R语言使用cox函数构建生存分析回归模型、使用subgroupAnalysis进行亚组分析并可视化森林图
- 为什么字符串一旦创建就不可以改变?
- egg.js中Class constructor BaseContextClass cannot be invoked without ‘new‘解决方法
猜你喜欢

color socks problem

小程序中计算距离信息

PEG derivative Biotin-PEG1-OH (cas: 95611-10-2, 2-biotinaminoethanol) advantage description

【LeetCode】求根节点到叶节点数字之和

UI遍历的初步尝试

HCIP——综合交换实验

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

【kali-密码攻击】(5.2.1)密码分析:Hash Identifier(哈希识别)

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

DALL·E-2是如何工作的以及部署自己的DALL·E模型
随机推荐
SonarQube升级记录:7.8->7.9->8.9
Fedora 36 dnf 安装ModSecurity和 OWASP 核心规则集
多线程之享元模式和final原理
【软考软件评测师】软件测试基础知识
ASEMI整流桥GBJ1010参数,GBJ1010规格,GBJ1010封装
ABAP 里文件操作涉及到中文字符集的问题和解决方案
sql实战积累
信息化和数字化的核心差异
Docker interview question 2--get the number of database connections and docker-compose
02| operator
ITK编译remote库
unity 报错 Unsafe code may only appear if compiling with /unsafe. Enable “Allow ‘unsafe‘ code“ in Pla
为什么字符串一旦创建就不可以改变?
Unity editor extension interface uses List
跳房子游戏
分析 20 个 veToken 生态系统协议 这种代币模型为何受欢迎?
基于Web的疫情隔离区订餐系统
Character Statistics Histogram
跨部门沟通的技巧
Moonbeam网络维护模式(Maintenance Mode)解读