阿里 对象存储OSS 云存储服务

1.简介

对象存储服务(Object Storage Service ,OSS) 是一种 海量、安全、低成本、高可靠的云存储服务,适合存放任意类型的文件。容量和处理能力弹性扩展,多种存储类型供选择,全面优化存储成本。

2.如何使用。参考文档

 

看文档,说的很明白,这里就不演示了

3. SpringCloudAlibaba-OSS

spring-cloud-alibaba/README-zh.md at 2022.x · alibaba/spring-cloud-alibaba · GitHub

好像新版本没有starter了

自己封装一下原生API吧

package com.jmj.gulimall.product.config;import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class OssClientConfiguration {@Value("${spring.cloud.alicloud.access-key}")private String accessKey;@Value("${spring.cloud.alicloud.secret-key}")private String secretKey;@Value("${spring.cloud.alicloud.endpoint}")private String endpoint;@Beanpublic OSS ossClient() {// 创建OSSClient实例。CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKey, secretKey);// 创建ClientBuilderConfiguration。// ClientBuilderConfiguration是OSSClient的配置类,可配置代理、连接超时、最大连接数等参数。ClientBuilderConfiguration conf = new ClientBuilderConfiguration();// 设置Socket层传输数据的超时时间,默认为50000毫秒。conf.setSocketTimeout(10000);// 设置建立连接的超时时间,默认为50000毫秒。conf.setConnectionTimeout(10000);// 设置失败请求重试次数,默认为3次。conf.setMaxErrorRetry(5);OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider,conf);return ossClient;}}
package com.jmj.gulimall.product.ossclient;import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;@Component
@Slf4j
public class OssClientTemplate {@Autowiredprivate OSS ossClient;public Boolean uploadFile(String bucketName, String objectName, File file) {// 创建PutObjectRequest对象。try {PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file);// 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。ObjectMetadata metadata = new ObjectMetadata();metadata.setHeader("x-oss-forbid-overwrite", true);// metadata.setObjectAcl(CannedAccessControlList.Private);putObjectRequest.setMetadata(metadata);// 上传文件。PutObjectResult result = ossClient.putObject(putObjectRequest);log.info("上传成功:文件名 {}", objectName);return true;} 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());}return false;}public Boolean uploadFile(String bucketName, String objectName, String content){// 创建PutObjectRequest对象。ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content.getBytes());try {PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, byteArrayInputStream);// 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。ObjectMetadata metadata = new ObjectMetadata();metadata.setHeader("x-oss-forbid-overwrite", true);// metadata.setObjectAcl(CannedAccessControlList.Private);putObjectRequest.setMetadata(metadata);// 上传文件。PutObjectResult result = ossClient.putObject(putObjectRequest);log.info("上传成功:文件名 {}", objectName);return true;} 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 (byteArrayInputStream!=null){try {byteArrayInputStream.close();} catch (IOException e) {e.printStackTrace();}}}return false;}public Boolean uploadFile(String bucketName, String objectName, InputStream inputStream){// 创建PutObjectRequest对象。try {PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);// 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。ObjectMetadata metadata = new ObjectMetadata();metadata.setHeader("x-oss-forbid-overwrite", true);// metadata.setObjectAcl(CannedAccessControlList.Private);putObjectRequest.setMetadata(metadata);// 上传文件。PutObjectResult result = ossClient.putObject(putObjectRequest);log.info("上传成功:文件名 {}", objectName);return true;} 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 (inputStream!=null){try {//其实流已经被关闭了,我再关闭一下保险一点inputStream.close();} catch (IOException e) {e.printStackTrace();}}}return false;}public Boolean uploadFile(String objectName, InputStream inputStream){// 创建PutObjectRequest对象。return uploadFile("gulimall-jmj", objectName, inputStream);}
}

4.后端签名直传

package com.jmj.gulimall.third.config;import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.jmj.gulimall.third.ossclient.OssClientTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
@EnableConfigurationProperties({OssConfigurationProperties.class})
@Slf4j
@RefreshScope //动态从配置中心获取配置
public class OssClientConfiguration {@Autowiredprivate OssConfigurationProperties ossConfigurationProperties;@Beanpublic OSS ossClient() {// 创建OSSClient实例。CredentialsProvider credentialsProvider = new DefaultCredentialProvider(ossConfigurationProperties.getAccessKey(), ossConfigurationProperties.getSecretKey());// 创建ClientBuilderConfiguration。// ClientBuilderConfiguration是OSSClient的配置类,可配置代理、连接超时、最大连接数等参数。ClientBuilderConfiguration conf = new ClientBuilderConfiguration();// 设置是否支持CNAME。CNAME用于将自定义域名绑定到目标Bucket。conf.setSupportCname(true);// 设置Socket层传输数据的超时时间,默认为50000毫秒。conf.setSocketTimeout(10000);// 设置建立连接的超时时间,默认为50000毫秒。conf.setConnectionTimeout(10000);// 设置失败请求重试次数,默认为3次。conf.setMaxErrorRetry(5);OSS ossClient = new OSSClientBuilder().build(ossConfigurationProperties.getEndpoint(), credentialsProvider, conf);log.info("ossClient初始化完成,properties={}",ossConfigurationProperties);return ossClient;}@Beanpublic OssClientTemplate ossClientTemplate(OSS ossClient) {return new OssClientTemplate(ossClient,ossConfigurationProperties);}}
package com.jmj.gulimall.third.config;import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;@ConfigurationProperties(prefix = "spring.cloud.alicloud")
@Data
@RefreshScope //动态从配置中心获取配置
public class OssConfigurationProperties {private String accessKey;private String secretKey;private String endpoint;private String regionEnd;private String bucket;}
package com.jmj.gulimall.third.controller;import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.jmj.gulimall.third.common.R;
import com.jmj.gulimall.third.config.OssConfigurationProperties;
import com.jmj.gulimall.third.ossclient.OssClientTemplate;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;@RestController
@Slf4j
@RequestMapping("/oss")
public class OssController {@Autowiredprivate OssClientTemplate ossClientTemplate;@Autowiredprivate OssConfigurationProperties properties;@GetMapping("/policy")public R policy(HttpServletRequest request, HttpServletResponse response) {// 设置上传回调URL,即回调服务器地址,用于处理应用服务器与OSS之间的通信。OSS会在文件上传完成后,把文件上传信息通过此回调URL发送给应用服务器。
//                String callbackUrl = "https://192.168.0.0:8888";// 设置上传到OSS文件的前缀,可置空此项。置空后,文件将上传至Bucket的根目录下。SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");String formatDate = simpleDateFormat.format(new Date());String dir = formatDate + "/";OSS ossClient = ossClientTemplate.getOssClient();String accessKeyId = properties.getAccessKey();String regionEnd = properties.getRegionEnd();String bucket = properties.getBucket();String host = "https://" + bucket + "." + regionEnd;try {long expireTime = 30;long expireEndTime = System.currentTimeMillis() + expireTime * 1000;Date expiration = new Date(expireEndTime);// PostObject请求最大可支持的文件大小为5 GB,即CONTENT_LENGTH_RANGE为5*1024*1024*1024。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 accessId = accessKeyId;String encodedPolicy = BinaryUtil.toBase64String(binaryData);String postSignature = ossClient.calculatePostSignature(postPolicy);Map<String, String> 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));return R.ok().put("data",respMap);} catch (Exception e) {// Assert.fail(e.getMessage());log.error(e.getMessage(), e);}return  R.error("上传签名异常");}}
package com.jmj.gulimall.third.ossclient;import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.jmj.gulimall.third.config.OssConfigurationProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;@Slf4j
public class OssClientTemplate {private OSS ossClient;public OSS getOssClient() {return ossClient;}private OssConfigurationProperties properties;public OssClientTemplate(OSS ossClient, OssConfigurationProperties properties) {this.ossClient = ossClient;this.properties = properties;}public Boolean uploadFile(String bucketName, String objectName, File file) {// 创建PutObjectRequest对象。try {PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, file);// 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。ObjectMetadata metadata = new ObjectMetadata();metadata.setHeader("x-oss-forbid-overwrite", true);// metadata.setObjectAcl(CannedAccessControlList.Private);putObjectRequest.setMetadata(metadata);// 上传文件。PutObjectResult result = ossClient.putObject(putObjectRequest);log.info("上传成功:文件名 {}", objectName);return true;} 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());}return false;}public Boolean uploadFile(String bucketName, String objectName, String content){// 创建PutObjectRequest对象。ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content.getBytes());try {PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, byteArrayInputStream);// 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。ObjectMetadata metadata = new ObjectMetadata();metadata.setHeader("x-oss-forbid-overwrite", true);// metadata.setObjectAcl(CannedAccessControlList.Private);putObjectRequest.setMetadata(metadata);// 上传文件。PutObjectResult result = ossClient.putObject(putObjectRequest);log.info("上传成功:文件名 {}", objectName);return true;} 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 (byteArrayInputStream!=null){try {byteArrayInputStream.close();} catch (IOException e) {e.printStackTrace();}}}return false;}public Boolean uploadFile(String bucketName, String objectName, InputStream inputStream){// 创建PutObjectRequest对象。try {PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);// 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。ObjectMetadata metadata = new ObjectMetadata();metadata.setHeader("x-oss-forbid-overwrite", true);// metadata.setObjectAcl(CannedAccessControlList.Private);putObjectRequest.setMetadata(metadata);// 上传文件。PutObjectResult result = ossClient.putObject(putObjectRequest);log.info("上传成功:文件名 {}", objectName);return true;} 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 (inputStream!=null){try {//其实流已经被关闭了,我再关闭一下保险一点inputStream.close();} catch (IOException e) {e.printStackTrace();}}}return false;}public Boolean uploadFile(String objectName, InputStream inputStream){// 创建PutObjectRequest对象。return uploadFile(properties.getBucket(), objectName, inputStream);}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/593433.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

elsint报错Delete `␍`eslintprettier/prettier

一&#xff0c;原因 这篇博客写得很清楚&#xff1a;解决VSCode Delete ␍eslint(prettier/prettier)错误_vscode 删除cr-CSDN博客 还有这篇文章&#xff0c;解决办法很详细&#xff1a;滑动验证页面 二&#xff0c;解决办法 根目录下新建.prettierrc.js文件 module.exports…

【国信华源2024年首场春季校园招聘面试会举办】

阳春三月&#xff0c;春意盎然&#xff0c;北京国信华源科技有限公司2024年校园招聘活动如期展开。4月2日&#xff0c;成功举办了“国信华源2024年首场春季校园招聘面试会”。 国信华源公司人力资源部热情接待了前来参加面试的同学们&#xff0c;并亲自陪同他们深入探访了企业。…

Redis中的Sentinel(一)

Sentinel 概述 Sentinel(哨岗、哨兵)是Redis的高可用性(high availability)解决方案:由一个或多个Sentinel实例(instance)组成的Sentinel系统(system)可以监视任意多个主服务器&#xff0c;以及这些主服务器属下的所有从服务器,并在被监视的主服务器进入下线状态时&#xff0…

DIY蓝牙键盘(1) - 理解 键盘报文(免费)

DIY蓝牙键盘(1) - 理解键盘报文 1. 键盘报文体验 一个键盘对于用户的体验是&#xff0c;用户按按键A他能看到字母A会在主机上显示出来。那这是如何实现的&#xff1f; 其实很简单&#xff0c;只要键盘发送下面的两个报文给主机&#xff0c;字母A就能在主机上显示出来。 (1)…

JS详解-手写Promise!!!

前言&#xff1a; 针对js的深入理解&#xff0c;作者学习并撰写以下文章&#xff0c;由于理解认知有限难免存在偏差&#xff0c;请大家指正&#xff01;所有定义来自mdn。 Promise介绍&#xff1a; 对象表示异步操作最终的完成&#xff08;或失败&#xff09;以及其结果值. 描…

python-基础篇-字符串、列表、元祖、字典-字符串

文章目录 2.3字符串、列表、元祖、字典2.3.1字符串2.3.1.1字符串介绍2.3.1.1.1python中字符串的格式&#xff1a;2.3.1.1.2字符串在内存中的存储方式 2.3.1.2字符串的输入输出2.3.1.2.1字符串输出2.3.1.2.2字符串输入2.3.1.2.3组字符串的方式 2.3.1.3下标和切片2.3.1.3.1下标索…

挖一挖:PostgreSQL Java里的double类型存储到varchar精度丢失问题

前言 大概故事是这样的&#xff0c;PostgreSQL数据库&#xff0c;表结构&#xff1a; create table t1(a varchar);然后使用标准的Java jdbc去插入数据&#xff0c;其基本代码如下&#xff1a; import java.sql.*; public class PgDoubleTest {public static void main(Stri…

聊聊测试用例评审流程

测试人员将需求熟悉完成后&#xff0c;开始编写相应的测试用例&#xff0c;待测试用例编写完成后只是测试用例完成前的第一步&#xff0c;后边的流程需要组织线上或线下评审会议等等。 首先要了解测试用例评审的最终目的是什么&#xff1a;提高测试用例的质量和覆盖率&#xff…

学浪里面的视频怎么保存到本地

很多人都在学浪里面买了课程,可是却找不到下载学浪课程的方法&#xff0c;这里Leo小黑教大家如何把学浪里购买的视频课程下载下来 注意:此方法不可以下载直播回放 1.解压我给大家准备的小浪助手.exe 2.打开小浪助手.exe 3.要是有抖音账号和学浪绑定的手机账号一样那就可以直接…

3.6k star, 免费开源跨平台的数据库管理工具 dbgate

3.6k star, 免费开源跨平台的数据库管理工具 dbgate 分类 开源分享 项目名: dbgate -- 免费开源跨平台的数据库管理工具 Github 开源地址&#xff1a; GitHub - dbgate/dbgate: Database manager for MySQL, PostgreSQL, SQL Server, MongoDB, SQLite and others. Runs under…

Python如何解决“滑动拼图”验证码(8)

前言 本文是该专栏的第67篇,后面会持续分享python爬虫干货知识,记得关注。 做过爬虫项目的同学,或多或少都会接触到一些需要解决验证码才能正常获取数据的平台。 在本专栏之前的文章中,笔者有详细介绍通过python来解决多种“验证码”(点选验证,图文验证,滑块验证,滑块…

【Java笔记】多线程0:JVM线程是用户态还是内核态?Java 线程与OS线程的联系

文章目录 JVM线程是用户态线程还是内核态线程什么是用户态线程与内核态线程绿色线程绿色线程的缺点 线程映射稍微回顾下线程映射模型JVM线程映射 线程状态操作系统的线程状态JVM的线程状态JVM线程与OS线程的状态关系 Reference 今天复盘一下Java中&#xff0c;JVM线程与实际操作…