Bucket(存储空间)
:用于存储对象的容器,所有对象都属于某个存储空间中,一般是一个项目创建一个Bucket来专门存储该项目的文件Object(对象)
:可以理解为文件,对象在Bucket内部由唯一的Key来标识Region(地域)
:选择数据所存放的物理地址,如北京Endpoint(访问域名)
:对外服务的访问域名,不同Region的域名不同,通过内网和外网访问相同Region的域名也不同AccessKey(访问密钥)
:简称AK,指的是身份验证中使用的AccessKeyId和AccessKeySecret描述
:用户现在客户端将文件上传到应用所部署的服务器,然后服务器再将文件上传到OSS中,OSS存储文件之后,返回文件地址给应用服务器,应用服务器接着将文件地址存储到数据库中。后续需要访问文件,直接从数据库中查询出访问地址,然后直接访问即可。
缺点
:需要将文件上传至应用服务器,消耗应用服务器的资源,应用服务器压力大
描述
:直接将OSS的相关密钥存储到js中,直接使用js方法上传文件,用户直接在客户端就将文件上传到OSS
缺点
:不安全,密钥容易被获取,不法分子可能会恶意刷流量,没办法限流
描述
:客户端向应用服务器获取签名,然后凭借签名直接将文件上传到OSS
优点
:安全,且节省应用服务器性能
<dependency>
<groupId>com.aliyun.ossgroupId>
<artifactId>aliyun-sdk-ossartifactId>
<version> 3.10.2version>
dependency>
oss.accessKeyId=你的accessKeyId
oss.accessKeySecret=你的accessKeySecret
oss.endpoint=你的域名
oss.bucketName=你的存储空间
用来加载配置文件里面的配置,创建OSS对象并创建Bean
package com.shm.config;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OSSConfig {
@Value("${oss.endpoint}")
private String endpoint;
@Value("${oss.accessKeyId}")
private String accessKeyId;
@Value("${oss.accessKeySecret}")
private String accessKeySecret;
@Bean
public OSS ossClient() {
return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
}
}
【接口】
package com.shm.service;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.stereotype.Service;
public interface OssService {
/**
* 获取签名
* @return
*/
public AjaxResult getPolicy();
}
【实现类】
package com.shm.service.impl;
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.ruoyi.common.core.domain.AjaxResult;
import com.shm.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
@Service
public class OssServiceImpl implements OssService {
@Autowired
private OSS ossClient;
@Value("${oss.bucketName}")
private String bucketName;
@Value("${oss.endpoint}")
private String endpoint;
@Value("${oss.accessKeyId}")
private String accessId;
@Override
public AjaxResult getPolicy() {
// 拼接出Host地址
String host = "https://" + bucketName + "." + endpoint;
Map<String, String> respMap = null;
try {
/// 设置过期时间
// 秒数,这里设置10秒就过期
long expireTime = 10;
long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
Date expiration = new Date(expireEndTime);
/// 指定请求的条件
PolicyConditions policyConditions = new PolicyConditions();
// 设置内容长度允许的字节数,最大是1048576000个字节,1MB=1048576个字节,这里限制最大是100MB
policyConditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 104857600);
// 限制上传文件的前缀
// 设置文件夹,这里按照日期分文件夹
String dir = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/";
policyConditions.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
/// 生成policy
String postPolicy = ossClient.generatePostPolicy(expiration, policyConditions);
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) {
System.out.println(e.getMessage());
}
return AjaxResult.success("获取凭证成功", respMap);
}
}
package com.shm.controller;
import com.ruoyi.common.core.domain.AjaxResult;
import com.shm.service.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/thirdParty/oss")
@Api("OssController")
public class OssController {
@Autowired
private OssService ossService;
@ApiOperation("获取OSS凭证")
@GetMapping("/policy")
@PreAuthorize("@ss.hasPermi('thirdParty:oss:policy')")
public AjaxResult policy() {
return ossService.getPolicy();
}
}
该组件基于若依管理系统前端项目所提供的图片上传组件修改,原组件采用直传方式
,改动后采用签名后直传
的方式
<template>
<div class="component-upload-image">
<el-upload
multiple
:action="uploadImgUrl"
:data="dataObj"
list-type="picture-card"
:on-success="handleUploadSuccess"
:before-upload="handleBeforeUpload"
:limit="limit"
:on-error="handleUploadError"
:on-exceed="handleExceed"
ref="imageUpload"
:before-remove="handleDelete"
:show-file-list="true"
:headers="headers"
:file-list="fileList"
:on-preview="handlePictureCardPreview"
:class="{ hide: fileList.length >= limit }"
>
<el-icon class="avatar-uploader-icon">
<plus/>
el-icon>
el-upload>
<div class="el-upload__tip" v-if="showTip">
请上传
<template v-if="fileSize">
大小不超过 <b style="color: #f56c6c">{{ fileSize }}MBb>
template>
<template v-if="fileType">
格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}b>
template>
的文件
div>
<el-dialog
v-model="dialogVisible"
title="预览"
width="800px"
append-to-body
>
<img
:src="dialogImageUrl"
style="display: block; max-width: 100%; margin: 0 auto"
/>
el-dialog>
div>
template>
<script setup>
import {getToken} from "@/utils/auth";
import ossApi from '@/api/thirdParty/oss'
import uuidApi from '@/utils/uuid'
const props = defineProps({
modelValue: [String, Object, Array],
// 图片数量限制
limit: {
type: Number,
default: 5,
},
// 大小限制(MB)
fileSize: {
type: Number,
default: 5,
},
// 文件类型, 例如['png', 'jpg', 'jpeg']
fileType: {
type: Array,
default: () => ["png", "jpg", "jpeg"],
},
// 是否显示提示
isShowTip: {
type: Boolean,
default: true
},
});
const {proxy} = getCurrentInstance();
const emit = defineEmits();
const number = ref(0);
const uploadList = ref([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(import.meta.env.VITE_APP_OSS_PATH); // 上传的图片服务器地址
const headers = ref({Authorization: "Bearer " + getToken()});
const fileList = ref([]);
const showTip = computed(
() => props.isShowTip && (props.fileType || props.fileSize)
);
let dataObj = {
policy: '',
signature: '',
key: '',
OSSAccessKeyId: '',
dir: '',
host: ''
};
watch(() => props.modelValue, val => {
if (val) {
// 首先将值转为数组
const list = Array.isArray(val) ? val : props.modelValue.split(",");
console.log("list:" + JSON.stringify(list));
// 然后将数组转为对象数组
fileList.value = list.map(item => {
if (typeof item === "string") {
item = {url: item};
}
return item;
});
console.log("fileList:" + JSON.stringify(fileList));
} else {
fileList.value = [];
return [];
}
}, {deep: true, immediate: true});
// 上传前loading加载
function handleBeforeUpload(file) {
let isImg = false;
if (props.fileType.length) {
let fileExtension = "";
if (file.name.lastIndexOf(".") > -1) {
fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
}
isImg = props.fileType.some(type => {
if (file.type.indexOf(type) > -1) return true;
if (fileExtension && fileExtension.indexOf(type) > -1) return true;
return false;
});
} else {
isImg = file.type.indexOf("image") > -1;
}
if (!isImg) {
proxy.$modal.msgError(
`文件格式不正确, 请上传${props.fileType.join("/")}图片格式文件!`
);
return false;
}
if (props.fileSize) {
const isLt = file.size / 1024 / 1024 < props.fileSize;
if (!isLt) {
proxy.$modal.msgError(`上传头像图片大小不能超过 ${props.fileSize} MB!`);
return false;
}
}
//获取OSS签名
return new Promise((resolve, reject) => {
ossApi.getPolicy()
.then((response) => {
console.log('policy response:' + JSON.stringify(response))
// debugger;
dataObj.policy = response.data.policy
dataObj.signature = response.data.signature
dataObj.OSSAccessKeyId = response.data.accessId
dataObj.key = response.data.dir + uuidApi.getUUID() + '_${filename}'
dataObj.dir = response.data.dir
dataObj.host = response.data.host
console.log('获取policy成功')
// console.log('dataObj:' + JSON.stringify(dataObj))
// console.log("uploadImgUrl:" + import.meta.env.VITE_APP_OSS_PATH)
proxy.$modal.loading("正在上传图片,请稍候...");
number.value++;
resolve(true)
})
.catch((err) => {
console.log('获取policy失败')
reject(false)
})
})
}
// 文件个数超出
function handleExceed() {
proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}
// 上传成功回调
function handleUploadSuccess(res, file) {
console.log("handleUploadSuccess," + JSON.stringify(res) + JSON.stringify(file))
uploadList.value.push({
name: file.name, url: dataObj.host +
'/' +
dataObj.key.replace('${filename}', file.name)
});
console.log("上传成功")
uploadedSuccessfully();
}
// 删除图片
function handleDelete(file) {
const findex = fileList.value.map(f => f.name).indexOf(file.name);
if (findex > -1 && uploadList.value.length === number.value) {
fileList.value.splice(findex, 1);
let urlList = getUrlList(fileList);
emit("update:modelValue", urlList);
return false;
}
}
// 上传结束处理
function uploadedSuccessfully() {
console.log("number.value:" + number.value);
if (number.value > 0 && uploadList.value.length === number.value) {
//将新上传的图片添加到fileList
for (let i = 0; i < uploadList.value.length; i++) {
fileList.value.push(uploadList.value[i]);
}
//将所有图片的url拿出来,形成一个集合
let urlList = getUrlList(fileList);
uploadList.value = [];
number.value = 0;
emit("update:modelValue", urlList);
proxy.$modal.closeLoading();
}
}
// 上传失败
function handleUploadError() {
proxy.$modal.msgError("上传图片失败");
proxy.$modal.closeLoading();
}
// 预览
function handlePictureCardPreview(file) {
dialogImageUrl.value = file.url;
dialogVisible.value = true;
}
function getUrlList(fileList) {
let urlList = [];
for (let i = 0; i < fileList.value.length; i++) {
urlList.push(fileList.value[i].url);
}
return urlList;
}
script>
<style scoped lang="scss">
// .el-upload--picture-card 控制加号部分
:deep(.hide .el-upload--picture-card) {
display: none;
}
style>
下面的代码即去配置文件中读取图片上传地址,我使用读取配置的方式主要是为了方便部署时的环境切换,也可以直接写在组件里面,打包部署时修改会繁琐一点,也会容易遗忘
const uploadImgUrl = ref(import.meta.env.VITE_APP_OSS_PATH); // 上传的图片服务器地址
下面的代码的作用是将值同步给组件v-model所绑定的变量中
emit("update:modelValue", urlList);
【OSS请求API】
import request from '@/utils/request'
/*
菜单管理相关的API请求函数
*/
const api_name = '/thirdParty/oss'
export default {
getPolicy(data) {
return request({
url: `${api_name}/policy`,
method: "get",
params: data
})
},
}
【oss生成API】
/**
* 获取uuid
*/
export default {
getUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
})
}
}
使用UUID的作用主要是:用户上传的图片名称可能一样,但是图片内容不同,在名称前面添加UUID可以避免文件名冲突,如下图
使用,通过v-model绑定变量,值的形式是url数组。limit="1"
的作用是限制只能上传一张图片
<imageUpload v-model="form.logo" limit="1">imageUpload>
查看组件的代码,limit
fileSize
fileType
isShowTip
这个值都是可以设置的,具体的含义请查看下图
这个组件的功能还是比较完善的,具体效果可以查看下面的效果图
【上传图片之前】
【上传图片成功后】
【上传成功的图片可以预览和删除】