引入阿里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)
//使用本地上傳的視頻來(lái)獲取第一幀
this.findVideoPoster(file).then((ret) => {
//打印封面圖鏈接
console.log(ret)
})
}).catch(() => {})
}
文件上傳時(shí)重命名
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啡浊、預(yù)覽圖的寬高
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') //轉(zhuǎn)換為base64觅够,圖片格式默認(rèn)為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轉(zhuǎn)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 })
}