- 引入依赖
npm install ali-oss --save
- OSS配置文件(config/ali-oss.ts)
// 引入oss
import OSS from 'ali-oss'
// 实例化 OSS: 创建OSS对象
export const clint = new OSS({
bucket: '自己的bucket', //bucket名称
region: 'oss-cn-beijing', //区域
endpoint: 'oss-cn-beijing.aliyuncs.com', //地域节点 ===> 外网访问
accessKeyId: 'accessKeyId', //访问键ID
accessKeySecret: 'accessKeySecret', //访问密钥
secure: true //如果是http默认就是false,如果是https就要写成true
})
- 写一个组件
<template>
<div >
<el-upload v-model:file-list="fileList" multiple :http-request="upload" class="upload-demo">
<el-button type="primary">Click to upload</el-button>
<template #tip>
<div class="el-upload__tip">jpg/png files with a size less than 500KB.</div>
</template>
</el-upload>
</div>
</template>
<script setup lang="ts" name="仪表盘">
import utils from '@renderer/utils'
import { ref } from 'vue'
const fileList = ref([]) // 上传文件列表
// 上传操作
const upload = options => {
console.log('点击上传==>', options)
utils.oss.upload(options.file)
}
</script>
- 在工具类中
npm i nanoid
const utils = {}
utils.oss = {
//上传方法
upload(file) {
const uuid = nanoid()
// 截取文件后缀名
let index = file.name.lastIndexOf('.')
const suffix = file.name.substring(index + 1)
// 上传的文件名称
let fileName = uuid + '.' + suffix
// 当前时间
let currentDate = utils.getTime(new Date(), 'yyyy-MM-dd')
// 存放文件的路径
let fileIpc = 'bucket里面的/' + currentDate + '/' + fileName
// 参数1:存放路径;参数2:文件对象;参数3:是上传操作对象
clint
.multipartUpload(fileIpc, file, {
progress: function (p, cpt, res) {
console.log(p, cpt, res)
}
})
.then(res => {
if (res.res.status == 200) {
ElMessage({
message: '上传成功',
type: 'success'
})
}
})
}
}
// 时间戳转换成标准时间
utils.getTime = (date, fmt = 'yyyy-MM-dd hh:mm:ss') => {
date = new Date(date)
var o = {
'M+': date.getMonth() + 1, //月份
'd+': date.getDate(), //日
'h+': date.getHours(), //小时
'm+': date.getMinutes(), //分
's+': date.getSeconds(), //秒
'q+': Math.floor((date.getMonth() + 3) / 3), //季度
S: date.getMilliseconds() //毫秒
}
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
for (var k in o) {
if (new RegExp('(' + k + ')').test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
)
}
}
return fmt
}
export default utils