1、引入ossSDK
npm i ali-oss
2、示例代码
<template>
<el-upload
ref="upload"
class="upload-demo"
action="#"
:limit="1"
:on-exceed="handleExceed"
:http-request="fnUploadRequest"
:before-upload="handleUpload"
:auto-upload="true"
>
<template #trigger>
<el-button type="primary">选择文件</el-button>
</template>
<template #tip>
<div style="margin-left: 90px;margin-top: -30px;color: #E69F36">
说明:仅支持jpg、jpeg、bmp、png图片格式。图片大小不可超过5M
</div>
</template>
</el-upload>
</template>
<script setup>
import {onMounted, ref, reactive } from 'vue'
import OSS from 'ali-oss';
import {ElMessage, ElMessageBox, ElNotification} from "element-plus";
import {getOssSts } from "@/api/bill/auditBill.js";
const fileUrl = ref(null);
//校验
const handleUpload = (file, fileList) => {
// console.log(file, fileList);
var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
const extension = testmsg === 'png' || testmsg === 'jpg' || testmsg === 'doc' || testmsg === 'docx'
|| testmsg === 'ppt' || testmsg === 'pptx' || testmsg === 'xlsx' || testmsg === 'xls' || testmsg === 'rar'
|| testmsg === 'zip' || testmsg === 'pdf';
const isLimit10M = file.size / 1024 / 1024 < 5;
var bool = false;
if(extension && isLimit10M){
bool = true;
} else {
bool = false;
}
if(!extension) {
ElNotification.error('请选择附件文件类型!');
return bool;
}
if(!isLimit10M) {
ElNotification.error('上传失败,不能超过5M!');
return bool;
}
return bool;
}
//随机名称
function random_string(len) {
len = len || 32
var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
var maxPos = chars.length
var pwd = ''
for (let i = 0; i < len; i++) {
pwd += chars.charAt(Math.floor(Math.random() * maxPos))
}
return pwd
}
//上传
const fnUploadRequest = async (options) => {
try {
console.log('111')
console.log(options);
let file = options.file; // 拿到 file
const objName = `${random_string(6)}_${file.name}`;
//获取临时凭证
let config = await getOssSts();
console.log(config)
let client = new OSS({
region: config.data.data.region,
//云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,部署在服务端使用RAM子账号或STS,部署在客户端使用STS。
accessKeyId: config.data.data.accessKeyId,
accessKeySecret: config.data.data.accessKeySecret,
bucket: config.data.data.bucketName,
stsToken:config.data.data.securityToken,
// refreshSTSToken: async () => {
// // 向您搭建的STS服务获取临时访问凭证。
// const info = await fetch('your_sts_server');
// return {
// accessKeyId: info.accessKeyId,
// accessKeySecret: info.accessKeySecret,
// stsToken: info.stsToken
// }
// },
// 刷新临时访问凭证的时间间隔,单位为毫秒。
refreshSTSTokenInterval: 300000,
});
//上传
let result = await client.put(objName, file);
// let res = await put(objName, file)
console.log(result);
// 返回数据
// this.$emit("fileData", res);
fileUrl = result.url;
ElMessage({
type: 'success',
message: '上传附件成功!',
})
} catch (e) {
console.log('222')
ElNotification.error('上传附件失败!');
}
}
</script>