Alibaba Cloud OSS 公式 Web サイト: OSS 管理コンソール (aliyun.com)
オブジェクトストレージOSSとは
Alibaba Cloud Object Storage OSS (Object Storage Service) は、99.9999999999% (12 ナイン) のデータ耐久性と 99.995% のデータ可用性を提供できる、大規模で安全、低コスト、信頼性の高いクラウド ストレージ サービスです。ストレージ コストを完全に最適化するために、さまざまなストレージ タイプを使用できます。
OSS にはプラットフォームに依存しない RESTful API インターフェイスがあり、いつでもどこでも、あらゆる種類のデータをあらゆるアプリケーションに保存してアクセスできます。
Alibaba Cloud が提供する API、SDK インターフェイス、または OSS 移行ツールを使用して、大量のデータを Alibaba Cloud OSS との間で簡単に移動できます。データが Alibaba Cloud OSS に保存された後は、モバイル アプリケーション、大規模な Web サイト、画像共有、またはホットなオーディオとビデオの主なストレージ方法として標準ストレージ (標準) を選択することも、低コストで低頻度アクセスのストレージを選択することもできます。アクセス頻度の低いデータの保存方法として、より長い保存期間 (Infrequent Access)、アーカイブ ストレージ (Archive)、およびコールド アーカイブ ストレージ (Cold Archive) が使用されます。
1. アカウントを開設してスペースを作成する
- Alibaba Cloud アカウントを作成する
- オブジェクトストレージ OSS サービスをアクティブ化する
- OSS コンソールに入り、新しいOSS 管理コンソール (aliyun.com)バケットを作成します。
バケット名は任意に入力でき、リージョンは現在のリージョンに最も近いものを選択できます。テストなので、ストレージ タイプは低頻度アクセスを選択し、読み取りおよび書き込み権限にはアナウンス読み取りを選択します。
4. 作成が完了したら、右上隅をクリックして AccessKey を入力し、サブアカウント キーの使用を開始することを選択します。
5. サブアカウントを作成したら、生成したアカウントとキーを保管し、今後の運用にはこのサブアカウントを使用します。
6. エンドポイントおよびその他の情報は、コンソールの概要で確認できます。
2. Java で OSS クライアントを使用してファイルをサーバーにアップロードするだけです
- インポート依存関係 spring-cloud-starter-alicloud-oss
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alicloud-oss</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
2. 構成の追加 (アクセスキー、秘密キー、エンドポイント)
spring:
cloud:
alicloud:
access-key: 你的 access-key
secret-key: 你的 secret-key
oss:
endpoint: oss-cn-shenzhen.aliyuncs.com
注: エンドポイントは oss パッケージの下にあります
3. OSS サーバーへの画像のアップロードをテストするテスト クラスを作成します。
@Resource
OSS ossClient;
@Test
public void uploadDemo() throws FileNotFoundException {
// 填写Bucket名称,例如examplebucket。
String bucketName = "hola76";
// 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
String objectName = "1111727083.jpg";
// 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
// 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
String filePath= "C:\\Users\\Administrator\\Pictures\\111727083.jpg";
// 创建OSSClient实例。
//OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
InputStream inputStream = new FileInputStream(filePath);
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, inputStream);
System.out.println("上传成功!");
ossClient.shutdown();
}
4. コンソールに移動して表示します
5. 画像が正常にアップロードされました
3. サーバー側署名の直接送信とアップロードコールバックの設定
公式ドキュメント:サーバー側の署名と直接送信 (aliyun.com)
1.工程紹介
プロセスを次の図に示します。
ユーザーがOSSにファイルをアップロードし、アップロード結果をアプリケーションサーバーに返したい場合、アプリケーションサーバーにリクエストを通知するコールバック関数を設定する必要があります。ユーザーがファイルをアップロードした後、戻り結果を直接取得するのではなく、まずアプリケーション サーバーに通知し、その後結果をユーザーに伝えます。
2.JAVAの実装
1. サードパーティサービスを提供するための新しいプロジェクトを作成します。プロジェクトの構造は次のとおりです。
2. Alibaba Cloud OSS の依存関係と openFeign の依存関係を導入します (サービスの登録と検出は共通に含まれます)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.liucan.gulimall</groupId>
<artifactId>gulimall-third-party</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>gulimall-third-party</name>
<description>第三方服务</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.7.RELEASE</spring-boot.version>
<spring-cloud.version>Hoxton.SR9</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>com.liucan.gulimall</groupId>
<artifactId>gulimall-common</artifactId>
<version>0.0.1-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</exclusion>
<exclusion>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alicloud-oss</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
<exclusion>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.8.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.7.RELEASE</version>
<configuration>
<mainClass>com.liucan.gulimall.thirdparty.GulimallThirdPartyApplication</mainClass>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
3. @EnableDiscoveryClient をスタートアップ クラスに追加してサービスの登録と検出を有効にし、application.yml で登録センターのアドレスを構成します。
spring:
application:
name: gulimall-third-party
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
server:
port: 30000
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableDiscoveryClient
@SpringBootApplication
public class GulimallThirdPartyApplication {
public static void main(String[] args) {
SpringApplication.run(GulimallThirdPartyApplication.class, args);
}
}
4. nacos と入力し、サードパーティのdataIdを使用して現在のサービスの新しい名前空間を作成します 。
5. nacos [構成管理]--[構成リスト]で、先ほど作成した サードパーティの名前空間に切り替えて、新しい構成を作成します。
構成は次のとおりです。
6.プロジェクトリソースの下に新しいbootstrap.propertiesを作成し、構成センターのアドレスと読み取る名前空間を指定します。
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
spring.cloud.nacos.config.namespace=be8c72c0-916d-4bd8-8f80-14916ade1faf
spring.cloud.nacos.config.extension-configs[0].data-id=oss.yml
spring.cloud.nacos.config.extension-configs[0].group=DEFAULT_GROUP
spring.cloud.nacos.config.extension-configs[0].refresh=true
7. 新しい OSSContrller テストを作成してポリシー署名を取得します
package com.liucan.gulimall.thirdparty.controller;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
@RestController
public class OSSCntroller {
@Autowired
OSS ossClient;
@Value("${spring.cloud.alicloud.oss.endpoint}")
private String endpoint;
@Value("${spring.cloud.alicloud.access-key}")
private String accessId;
@Value("${spring.cloud.alicloud.secret-key}")
private String accessKey;
@Value("${spring.cloud.alicloud.oss.bucket}")
private String bucket;
@RequestMapping("/oss/policy")
public Map<String, String> policy(){
// 填写Host地址,格式为https://bucketname.endpoint。
String host = "https://"+bucket+"."+endpoint;
// 设置上传回调URL,即回调服务器地址,用于处理应用服务器与OSS之间的通信。OSS会在文件上传完成后,把文件上传信息通过此回调URL发送给应用服务器。
String callbackUrl = "https://192.168.0.0:8888";
// 设置上传到OSS文件的前缀,可置空此项。置空后,文件将上传至Bucket的根目录下。
String dateDir = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String dir = dateDir+"/";
// 创建ossClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
Map<String, String> respMap = null;
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);
} catch (Exception e) {
// Assert.fail(e.getMessage());
System.out.println(e.getMessage());
}
return respMap;
}
}
8. localhost:30000/oss/policyをリクエストします。
署名を正常に取得した後、ユーザーは画像をアップロードする前に最初にこのインターフェイスをリクエストし、次にこのインターフェイスから返された署名を使用して Alibaba Cloud に直接リクエストします。その後、Alibaba Cloud OSS に直接アップロードできます。ファイル ストリームは必要ありません。弊社サーバーに保存して転送するサーバー側署名直接送信です。
9. 統合ルーティング管理のためにサービスをゲートウェイに引き渡す
1. ゲートウェイモジュールにルーティング設定を追加します。
OSS サービスにアクセスするための統一された入り口は api/ thirdparty/ です。
spring:
cloud:
gateway:
routes:
- id: product_route
uri: lb://gulimall-product #lb開啓負載均衡 路由到服務名為gulimall_product的服务
predicates:
- Path=/api/product/**
filters:
- RewritePath=/api/product/(?<segment>/?.*),/product/$\{segment}
- id: third_party_route
uri: lb://gulimall-third-party #lb開啓負載均衡 路由到服務名為gulimall-third-party的服务
predicates:
- Path=/api/thirdparty/**
filters:
- RewritePath=/api/thirdparty/(?<segment>/?.*),/$\{segment}
- id: admin_route
uri: lb://renren-fast #lb開啓負載均衡 路由到服務名為renren-fast的服务
predicates:
- Path=/api/**
filters:
- RewritePath=/api/(?<segment>/?.*),/renren-fast/$\{segment}
2. ゲートウェイを再起動してアクセスします。
4. OOS フロントエンドとバックエンドの共同デバッグ テストのアップロード
1. src/components に新しいフォルダーアップロードを追加して、アップロードされたコンポーネントを保存します。
ポリシー.js:
import http from '@/utils/httpRequest.js'
export function policy() {
return new Promise((resolve,reject)=>{
http({
url: http.adornUrl("/thirdparty/oss/policy"),
method: "get",
params: http.adornParams({})
}).then(({ data }) => {
resolve(data);
})
});
}
singleUpload.vue: (アップロード パスをバケットのパブリック ドメイン名に変更します。これは OSS コンソールで表示できます)
<template>
<div>
<el-upload action="http://hola76.oss-cn-shenzhen.aliyuncs.com" :data="dataObj" list-type="picture" :multiple="false" :show-file-list="showFileList" :file-list="fileList" :before-upload="beforeUpload" :on-remove="handleRemove" :on-success="handleUploadSuccess" :on-preview="handlePreview">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过10MB</div>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="fileList[0].url" alt="">
</el-dialog>
</div>
</template>
<script>
import { policy } from './policy'
import { getUUID } from '@/utils'
export default {
name: 'singleUpload',
props: {
value: String
},
computed: {
imageUrl() {
return this.value
},
imageName() {
if (this.value != null && this.value !== '') {
return this.value.substr(this.value.lastIndexOf('/') + 1)
} else {
return null
}
},
fileList() {
return [
{
name: this.imageName,
url: this.imageUrl
}
]
},
showFileList: {
get: function () {
return this.value !== null && this.value !== '' && this.value !== undefined
},
set: function (newValue) {}
}
},
data() {
return {
dataObj: {
policy: '',
signature: '',
key: '',
ossaccessKeyId: '',
dir: '',
host: ''
// callback:'',
},
dialogVisible: false
}
},
methods: {
emitInput(val) {
this.$emit('input', val)
},
handleRemove(file, fileList) {
this.emitInput('')
},
handlePreview(file) {
this.dialogVisible = true
},
beforeUpload(file) {
let _self = this
return new Promise((resolve, reject) => {
policy()
.then(response => {
_self.dataObj.policy = response.data.policy
_self.dataObj.signature = response.data.signature
_self.dataObj.ossaccessKeyId = response.data.accessid
_self.dataObj.key = response.data.dir + '/' + getUUID() + '_${filename}'
_self.dataObj.dir = response.data.dir
_self.dataObj.host = response.data.host
resolve(true)
})
.catch(err => {
reject(false)
})
})
},
handleUploadSuccess(res, file) {
console.log('上传成功...')
this.showFileList = true
this.fileList.pop()
this.fileList.push({ name: file.name, url: this.dataObj.host + '/' + this.dataObj.key.replace('${filename}', file.name) })
this.emitInput(this.fileList[0].url)
}
}
}
</script>
<style>
</style>
multiUpload.vue: (アップロード パスをバケットのパブリック ドメイン名に変更します。これは OSS コンソールで表示できます)
<template>
<div>
<el-upload action="http://hola76.oss-cn-shenzhen.aliyuncs.com" :data="dataObj" list-type="picture-card" :file-list="fileList" :before-upload="beforeUpload" :on-remove="handleRemove" :on-success="handleUploadSuccess" :on-preview="handlePreview" :limit="maxCount" :on-exceed="handleExceed">
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt />
</el-dialog>
</div>
</template>
<script>
import { policy } from './policy'
import { getUUID } from '@/utils'
export default {
name: 'multiUpload',
props: {
//图片属性数组
value: Array,
//最大上传图片数量
maxCount: {
type: Number,
default: 30
}
},
data() {
return {
dataObj: {
policy: '',
signature: '',
key: '',
ossaccessKeyId: '',
dir: '',
host: '',
uuid: ''
},
dialogVisible: false,
dialogImageUrl: null
}
},
computed: {
fileList() {
let fileList = []
for (let i = 0; i < this.value.length; i++) {
fileList.push({ url: this.value[i] })
}
return fileList
}
},
mounted() {},
methods: {
emitInput(fileList) {
let value = []
for (let i = 0; i < fileList.length; i++) {
value.push(fileList[i].url)
}
this.$emit('input', value)
},
handleRemove(file, fileList) {
this.emitInput(fileList)
},
handlePreview(file) {
this.dialogVisible = true
this.dialogImageUrl = file.url
},
beforeUpload(file) {
let _self = this
return new Promise((resolve, reject) => {
policy()
.then(response => {
console.log('这是什么${filename}')
_self.dataObj.policy = response.data.policy
_self.dataObj.signature = response.data.signature
_self.dataObj.ossaccessKeyId = response.data.accessid
_self.dataObj.key = response.data.dir + '/' + getUUID() + '_${filename}'
_self.dataObj.dir = response.data.dir
_self.dataObj.host = response.data.host
resolve(true)
})
.catch(err => {
console.log('出错了...', err)
reject(false)
})
})
},
handleUploadSuccess(res, file) {
this.fileList.push({
name: file.name,
// url: this.dataObj.host + "/" + this.dataObj.dir + "/" + file.name; 替换${filename}为真正的文件名
url: this.dataObj.host + '/' + this.dataObj.key.replace('${filename}', file.name)
})
this.emitInput(this.fileList)
},
handleExceed(files, fileList) {
this.$message({
message: '最多只能上传' + this.maxCount + '张图片',
type: 'warning',
duration: 1000
})
}
}
}
</script>
<style>
</style>
2.brand.vue のコンポーネントの導入と使用
<single-upload></single-upload>
<script>
import singleUpload from '../../../components/upload/singleUpload.vue'
</script>
3.効果
Alibaba Cloud OSS のアップロード要求時にクロスドメインの問題が発生したことが判明しました。
4. OSS コンソールでクロスドメイン アクセスを有効にする
5. テスト
おおよそのプロセス: フロントエンドをクリックして画像をアップロード -> 署名データを取得するポリシーをリクエスト -> 署名データとファイル ストリームを Alibaba Cloud に送信 -> 検証と保存のために Alibaba Cloud