【系统开发】尚硅谷 - 谷粒商城项目笔记(三):OSS阿里云存储
上传的账号信息存储在应用服务器上传前先找应用服务器要一个policy上传策略,生成防伪签名添加依赖包测试获取需要填写的密钥信息完整测试代码阿里云sdk方式上传添加依赖在配置文件中添加用户id和密钥信息最后在测试类中,自动注入OSS接口,直接使用即可将oss配置加入nacos在pulic命名空间下,创建gulimall-third-party.properties(名字可以自定义),之所以放在pul
OSS阿里云存储
OSS基础配置
上传的账号信息存储在应用服务器
上传前先找应用服务器要一个policy上传策略,生成防伪签名
OSS跨域设置
原生sdk方式上传
添加依赖包
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.8.0</version>
</dependency>
测试
// Endpoint以广州为例,其它Region请按实际情况填写。
String endpoint = "http://oss-cn-guangzhou.aliyuncs.com";
// 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建。
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 上传文件流。
InputStream inputStream = new FileInputStream("<yourlocalFile>");
ossClient.putObject("<yourBucketName>", "<yourObjectName>", inputStream);
// 关闭OSSClient。
ossClient.shutdown();
获取需要填写的密钥信息
完整测试代码
@Test
void testOss() throws FileNotFoundException {
// Endpoint以广州为例,其它Region请按实际情况填写。
String endpoint = "http://oss-cn-guangzhou.aliyuncs.com";
// 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建。
String accessKeyId = "LTAI5tNTYKY13HpzJMFDmA2q";
String accessKeySecret = "ONbLcR0lw56HHKyZqkfIWeAiIM5VFO";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 上传文件流。
InputStream inputStream = new FileInputStream("C:\\Users\\WSKH\\Desktop\\test.png");
ossClient.putObject("gulimall-wskh", "原生sdk测试上传.png", inputStream);
// 关闭OSSClient。
ossClient.shutdown();
System.out.println("上传成功");
}
阿里云sdk方式上传
添加依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alicloud-oss</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
在配置文件中添加用户id和密钥信息
最后在测试类中,自动注入OSS接口,直接使用即可
@SpringBootTest
class GulimallProductApplicationTests {
@Autowired
BrandService brandService;
@Autowired
OSS ossClient;
@Test
void testOss() throws FileNotFoundException {
// 上传文件流。
InputStream inputStream = new FileInputStream("C:\\Users\\WSKH\\Desktop\\test.png");
ossClient.putObject("gulimall-wskh", "原生sdk测试上传2.png", inputStream);
// 关闭OSSClient。
ossClient.shutdown();
System.out.println("上传成功");
}
}
将oss配置加入nacos
在pulic命名空间下,创建gulimall-third-party.properties(名字可以自定义),之所以放在pulic下,而不是放在一个新建的命名空间下,是因为踩过坑,好像只有在pulic下才可以读取到(可能我没配置好环境)
配置中内容如下,格式采用properties而不是yml,一开始我是用yml无法正常获取配置信息,后改为properties就可以了
# 广州的地址
spring.cloud.alicloud.oss.endpoint=oss-cn-guangzhou.aliyuncs.com
# 入口令牌
spring.cloud.alicloud.access-key=xxx
# 密码令牌
spring.cloud.alicloud.secret-key=xxx
# 上传文件后要存储在哪个bucket中
spring.cloud.alicloud.oss.bucket=gulimall-wskh
然后是本地配置
# 服务名
spring.cloud.nacos.config.name=gulimall-third-party
# nacos地址
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
# 命名空间id 不写则默认使用pulic命名空间下的配置
#spring.cloud.nacos.config.namespace=47b926dd-dd1f-4552-b874-fd040045bb48
# 指明dataId
spring.cloud.nacos.config.extension-configs[0].data-id=gulimall-third-party.properties
# 分组设置,默认组即可
spring.cloud.nacos.config.extension-configs[0].group=DEFAULT_GROUP
# 是否自动刷新配置信息
spring.cloud.nacos.config.extension-configs[0].refresh=true
ok,一切准备就绪,让我们试一下
@RestController
public class OssController {
@Autowired
OSS ossClient;
@Value ("${spring.cloud.alicloud.oss.endpoint}")
String endpoint ;
@Value("${spring.cloud.alicloud.oss.bucket}")
String bucket ;
@Value("${spring.cloud.alicloud.access-key}")
String accessId ;
@Value("${spring.cloud.alicloud.secret-key}")
String accessKey ;
@RequestMapping("/oss/policy")
public Map<String, String> policy(){
String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String dir = format; // 用户上传文件时指定的前缀。
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));
} catch (Exception e) {
// Assert.fail(e.getMessage());
System.out.println(e.getMessage());
} finally {
ossClient.shutdown();
}
return respMap;
}
}
打开浏览器,输入http://localhost:7999/oss/policy,按回车,看到以下信息,说明配置成功啦
加入网关的路由分发
在网关路由分发的配置中加入以下配置:
- id: third_party_route
uri: lb://gulimall-third-party
predicates:
- Path=/api/thirdparty/**
filters:
- RewritePath=/api/thirdparty/(?<segment>/?.*),/$\{segment}
和前端整合测试
在前端的组件文件夹下创建upload文件夹,里面有三个文件,内容如下:
policy.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 单文件上传组件
<template>
<div>
<el-upload
action="http://gulimall-wskh.oss-cn-guangzhou.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 多文件上传组件
<template>
<div>
<el-upload
action="http://gulimall.oss-cn-shanghai.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>
在需要的界面引入组件
使用组件
查看效果
如果报错503的话,可以在第三方服务模块中引入以下依赖:
<!-- 解决503问题 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
更多推荐
所有评论(0)