安装 oss 模块:
npm install ali-oss
js 工具类
'use strict'
import Utils from '@/utils/utils'
var OSS = require('ali-oss')
export default {
/**
* 创建随机字符串
* @param num
* @returns {string}
*/
randomString(num) {
const chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
let res = ''
for (let i = 0; i < num; i++) {
var id = Math.ceil(Math.random() * 35)
res += chars[id]
}
return res
},
/**
* 创建oss客户端对象
* @returns {*}
*/
createOssClient() {
return new Promise((resolve, reject) => {
const client = new OSS({
region: 'oss-cn-hangzhou',
accessKeyId: 'LTAIPh***Jsq',
accessKeySecret: 'oxRf***enYKI5pmk',
bucket: 'gu***ta2'
})
resolve(client)
})
},
/**
* 文件上传
* @param option 参考csdn: https://blog.csdn.net/qq_27626333/article/details/81463139
*/
ossUploadFile(option, type) {
const file = option.file
const self = this
return new Promise((resolve, reject) => {
const date = Utils.dateFormat(new Date(), 'yyyyMMdd') // 当前时间
const dateTime = Utils.dateFormat(new Date(), 'ddhhmmss') // 当前时间
const randomStr = self.randomString(5)// 4位随机字符串
const extensionName = file.name.substr(file.name.indexOf('.')) // 文件扩展名
var fileName = ''
switch (type) {
case 1:
fileName = 'guoya-data/interview/exam/' + date + '/' + dateTime + '_' + randomStr + extensionName
break
case 2:
fileName = 'guoya-data/interview/audio/' + date + '/' + dateTime + '_' + randomStr + extensionName
break
case 3:
fileName = 'guoya-data/stuInfo/personalPicture/' + date + '/' + dateTime + '_' + randomStr + extensionName
break
case 4:
fileName = 'guoya-data/checkStudy/' + date + '/' + dateTime + '_' + randomStr + extensionName
break
default:
fileName = 'guoya-data/' + date + '/' + dateTime + '_' + randomStr + extensionName
}
// 执行上传
self.createOssClient().then(client => {
// 异步上传,返回数据
resolve({
fileName: file.name,
fileUrl: fileName
})
// 上传处理
// 分片上传文件
client.multipartUpload(fileName, file, {
progress: function(p) {
const e = {}
e.percent = Math.floor(p * 100)
// console.log('Progress: ' + p)
option.onProgress(e)
}
}).then((val) => {
// console.info(val)
if (val.res.statusCode === 200) {
option.onSuccess(val)
return val
} else {
option.onError('上传失败')
}
}, err => {
option.onError('上传失败')
reject(err)
})
})
})
}
}
时间工具类
/**
* 工具类
*/
export default {
/**
* 时间日期格式化
* @param format
* @returns {*}
*/
dateFormat(dateObj, format) {
const date = {
'M+': dateObj.getMonth() + 1,
'd+': dateObj.getDate(),
'h+': dateObj.getHours(),
'm+': dateObj.getMinutes(),
's+': dateObj.getSeconds(),
'q+': Math.floor((dateObj.getMonth() + 3) / 3),
'S+': dateObj.getMilliseconds()
}
if (/(y+)/i.test(format)) {
format = format.replace(RegExp.$1, (dateObj.getFullYear() + '').substr(4 - RegExp.$1.length))
}
for (const k in date) {
if (new RegExp('(' + k + ')').test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length === 1
? date[k] : ('00' + date[k]).substr(('' + date[k]).length))
}
}
return format
}
}
实际应用
<template>
<div class="app-container">
<el-upload
class="upload-demo"
action=""
:http-request="fnUploadRequest"
:on-success="handleVideoSuccess"
multiple
:limit="15"
:on-exceed="beyondFile"
>
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
</div>
</template>
<script>
import oss from '@/utils/aliOss'
export default {
methods: {
/**
* @description [fnUploadRequest 覆盖默认的上传行为,实现自定义上传]
* @param {object} option [上传选项]
* @return {null} [没有返回]
*/
async fnUploadRequest(option) {
oss.ossUploadFile(option, 1).then(file => {
console.log(file)
})
},
// 上传成功后
handleVideoSuccess(response, file, fileList) {
// todo
console.log(file.name)
console.log(file)
console.log(file.response.name)
},
// 添加了多个文件
beyondFile(files, fileList) {
this.$message.warning(`当前限制选择 9 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`)
}
}
}
</script>
<style lang="scss" scoped>
</style>
网友评论