引入阿里OSS
import { client } from '@/utils/common.js'
//common.js
import OSS from 'ali-oss'
export const client = new OSS({
bucket: 'tthunter',
accessKeyId: 'XXXXXXXXX',
accessKeySecret: 'XXXXXXXXX',
endpoint: 'XXXXXXXXX.aliyuncs.com',
region: 'XXXXXXXXX',
cname: true,
secure: true,
})
a-upload自定义上传
customRequest(action) {
const file = action.file
let fileName = this.resetName(file)
client.put(fileName, file).then((res) => {
//打印视频上传到阿里云OSS后的链接
console.log(res.url)
//使用本地上传的视频来获取第一帧
this.findVideoPoster(file).then((ret) => {
//打印封面图链接
console.log(ret)
})
}).catch(() => {})
}
文件上传时重命名
resetName(file) {
let ftype = file.type.substring(file.type.lastIndexOf('/') + 1)
return (String(new Date().getTime()) + parseInt(Math.random() * 100000) + '.' + ftype)
}
获取视频第一帧作为封面,file为antdv上传组件上传的视频
findVideoPoster(file) {
let self = this
return new Promise(function(resolve) {
let base64URL = ''
let video = document.createElement('video')
video.setAttribute('crossOrigin', 'anonymous') //处理跨域
video.setAttribute('src', URL.createObjectURL(file))
video.currentTime = 1
video.addEventListener('loadeddata', function() {
let canvas = document.createElement('canvas')
//使用视频的宽高作为canvas、预览图的宽高
let width = video.videoWidth
let height = video.videoHeight
canvas.width = width
canvas.height = height
canvas.getContext('2d').drawImage(video, 0, 0, width, height) //绘制canvas
base64URL = canvas.toDataURL('image/jpeg') //转换为base64,图片格式默认为png,这里修改为jpeg
let fileName = String(new Date().getTime()) + parseInt(Math.random() * 100000) + '.jpeg'
const imgfile = self.data64toFile(base64URL)
client.put(fileName, imgfile).then((res) => {
resolve(res.url)
}).catch((err) => {
resolve('')
})
})
})
}
base64转Blob
data64toFile(base64URL) {
const arr = base64URL.split(',')
const mime = arr[0].match(/:(.*?);/)[1]
const bstr = atob(arr[1])
let n = bstr.length
const u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new Blob([u8arr], { type: mime })
}