Commit 617a7828 by 姜鹏凯

aliyun oss

1 parent d6d9c9c5
...@@ -43,6 +43,7 @@ ...@@ -43,6 +43,7 @@
}, },
"dependencies": { "dependencies": {
"@riophae/vue-treeselect": "0.4.0", "@riophae/vue-treeselect": "0.4.0",
"ali-oss": "^6.17.1",
"awesome-qr": "^2.0.1-rc.0", "awesome-qr": "^2.0.1-rc.0",
"axios": "^0.26.0", "axios": "^0.26.0",
"benz-amr-recorder": "^1.1.3", "benz-amr-recorder": "^1.1.3",
......
<script> <script>
import { getCosConfig, getVideoPic } from '@/api/common' import { getCosConfig, getVideoPic } from '@/api/common'
import { dateFormat, uuid } from '@/utils/index' import { dateFormat, uuid } from '@/utils/index'
// import Video from 'video.js' // import Video from 'video.js'
import Cos from 'cos-js-sdk-v5' import Cos from 'cos-js-sdk-v5'
import BenzAMRRecorder from 'benz-amr-recorder' import BenzAMRRecorder from 'benz-amr-recorder'
import MP4Box from 'mp4box' import MP4Box from 'mp4box'
export default { import OSS from 'ali-oss'
components: {},
props: {
// 单文件上传时使用
fileUrl: {
type: String,
default: '',
},
fileName: {
type: String,
default: '',
},
// 多文件上传时使用,例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}] export default {
fileList: { components: {},
type: Array, props: {
default: () => [], // 单文件上传时使用
}, fileUrl: {
type: String,
default: ''
},
fileName: {
type: String,
default: ''
},
// 0 图片(image)、1 语音(voice)、2 视频(video),3 普通文件(file) // 多文件上传时使用,例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}]
type: { fileList: {
type: String, type: Array,
default: '0', default: () => []
validator: function (value) {
// 这个值必须匹配下列字符串中的一个
return ['0', '1', '2', '3'].includes(value)
}, },
},
// 上传文件大小不能超过 maxSize MB, 各类型有默认限制 参见: maxSizeDefault
maxSize: {
type: Number,
default: undefined,
},
// 图片的宽高像素限制 [width(number), height(number)],默认null不限制
maxImgPx: {
type: Array,
default: null, // () => [100, 100]
},
// 允许上传的文件格式后缀名 eg:["jpg", "png"],['*']为不限制,各类型有默认限制 参见: formatDefault
format: {
type: Array,
default: undefined,
},
// 选择上传文件类型, 用于过滤系统选择文件类型, 默认根据类型自动匹配:见 acceptAuto,
accept: {
type: String,
default: '',
},
// 是否能上传多个
multiple: {
type: Boolean,
default: false,
},
// multiple为true时有效,最多上传几个,默认不限制,最小为1
limit: {
type: Number,
default: undefined,
},
// onProgress: {
// type: Function,
// default: null,
// },
// beforeUpload: {
// type: Function,
// default: function() {
// return function() {}
// },
// },
// 图片操作 目前支持有 view:查看,remove:删除,download:下载 // 0 图片(image)、1 语音(voice)、2 视频(video),3 普通文件(file)
// action: { type: {
// type: Array, type: String,
// default: () => ["view", "remove"], default: '0',
// }, validator: function (value) {
}, // 这个值必须匹配下列字符串中的一个
data() { return ['0', '1', '2', '3'].includes(value)
return { }
loading: false, },
// 上传文件大小不能超过 maxSize MB, 各类型有默认限制 参见: maxSizeDefault
maxSize: {
type: Number,
default: undefined
},
// 图片的宽高像素限制 [width(number), height(number)],默认null不限制
maxImgPx: {
type: Array,
default: null // () => [100, 100]
},
// 允许上传的文件格式后缀名 eg:["jpg", "png"],['*']为不限制,各类型有默认限制 参见: formatDefault
format: {
type: Array,
default: undefined
},
// 选择上传文件类型, 用于过滤系统选择文件类型, 默认根据类型自动匹配:见 acceptAuto,
accept: {
type: String,
default: ''
},
// 是否能上传多个
multiple: {
type: Boolean,
default: false
},
// multiple为true时有效,最多上传几个,默认不限制,最小为1
limit: {
type: Number,
default: undefined
}
// onProgress: {
// type: Function,
// default: null,
// },
// beforeUpload: {
// type: Function,
// default: function() {
// return function() {}
// },
// },
// 图片操作 目前支持有 view:查看,remove:删除,download:下载
// action: {
// type: Array,
// default: () => ["view", "remove"],
// },
},
data() {
return {
loading: false,
fileUrlWatch: this.fileUrl, fileUrlWatch: this.fileUrl,
fileNameWatch: this.fileName, fileNameWatch: this.fileName,
fileListWatch: this.fileList, fileListWatch: this.fileList,
picUrl: '', // 视频第一帧 picUrl: '', // 视频第一帧
file: undefined, file: undefined,
speed: 0, // 上传网速 speed: 0, // 上传网速
percentage: 0, //上传进度 percentage: 0, //上传进度
// cos配置信息 // cos配置信息
cosConfig: { bucketName: '', cosImgUrlPrefix: '', region: '' }, cosConfig: { bucketName: '', cosImgUrlPrefix: '', region: '' },
cosInstance: undefined, // cos实例 cosInstance: undefined, // cos实例
} ossObj: undefined
}, }
watch: {
fileUrl: {
handler(value) {
this.fileUrlWatch = value
},
}, },
fileName: { watch: {
handler(value) { fileUrl: {
this.fileNameWatch = value handler(value) {
this.fileUrlWatch = value
}
}, },
}, fileName: {
fileList: { handler(value) {
handler(value) { this.fileNameWatch = value
this.fileListWatch = value }
}, },
fileList: {
handler(value) {
this.fileListWatch = value
}
},
loading(val) {
this.$emit('loadingChange', val)
}
}, },
loading(val) { computed: {
this.$emit('loadingChange', val) // 识别选择文件类型
}, acceptAuto() {
}, return ['image/*', 'amr/*', 'video/*'][this.type]
computed: { }
// 识别选择文件类型
acceptAuto() {
return ['image/*', 'amr/*', 'video/*'][this.type]
}, },
}, created() {
created() { getCosConfig().then((res) => {
getCosConfig().then((res) => { this.cosConfig = res
this.cosConfig = res console.log(this.cosConfig)
this.cosInstance = new Cos({ if (this.cosConfig.fileObject == 'tencentOss') {
SecretId: res.secretId, this.cosInstance = new Cos({
SecretKey: res.secretKey, SecretId: res.secretId,
SecretKey: res.secretKey
})
} else {
let region = this.cosConfig.region.split('//')[1]
this.ossObj = new OSS({
// yourRegion填写Bucket所在地域。Region填写为oss-cn-hangzhou。
region: region.split('.')[0],
// 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。
accessKeyId: this.cosConfig.secretId,
accessKeySecret: this.cosConfig.secretKey,
// 填写Bucket名称。
bucket: this.cosConfig.bucketName
})
}
}) })
}) },
}, mounted() {
mounted() { // const cosInstance = new Cos({
// const cosInstance = new Cos({ // // getAuthorization 必选参数
// // getAuthorization 必选参数 // getAuthorization: function (options, callback) {
// getAuthorization: function (options, callback) { // // 服务端例子:https://github.com/tencentyun/qcloud-cos-sts-sdk/blob/master/scope.md
// // 服务端例子:https://github.com/tencentyun/qcloud-cos-sts-sdk/blob/master/scope.md // // 异步获取临时密钥
// // 异步获取临时密钥 // var url = window.lwConfig.SYSTEM_API + '/file/get/config' // url替换成您自己的后端服务
// var url = window.lwConfig.SYSTEM_API + '/file/get/config' // url替换成您自己的后端服务 // var xhr = new XMLHttpRequest()
// var xhr = new XMLHttpRequest() // xhr.open('get', url, true)
// xhr.open('get', url, true) // xhr.setRequestHeader('Content-Type', 'application/json')
// xhr.setRequestHeader('Content-Type', 'application/json') // xhr.onload = function (e) {
// xhr.onload = function (e) { // try {
// try { // var data = JSON.parse(e.target.responseText)
// var data = JSON.parse(e.target.responseText) // var credentials = data.credentials
// var credentials = data.credentials // } catch (e) {}
// } catch (e) {} // if (!data || !credentials) {
// if (!data || !credentials) { // return console.error('credentials invalid:\n' + JSON.stringify(data, null, 2))
// return console.error('credentials invalid:\n' + JSON.stringify(data, null, 2)) // }
// } // callback({
// callback({ // TmpSecretId: decrypt(credentials.secretId),
// TmpSecretId: decrypt(credentials.secretId), // TmpSecretKey: credentials.secretKey,
// TmpSecretKey: credentials.secretKey, // SecurityToken: credentials.sessionToken,
// SecurityToken: credentials.sessionToken, // // 建议返回服务器时间作为签名的开始时间,避免用户浏览器本地时间偏差过大导致签名错误
// // 建议返回服务器时间作为签名的开始时间,避免用户浏览器本地时间偏差过大导致签名错误 // StartTime: data.startTime, // 时间戳,单位秒,如:1580000000
// StartTime: data.startTime, // 时间戳,单位秒,如:1580000000 // ExpiredTime: data.expiredTime, // 时间戳,单位秒,如:1580000000
// ExpiredTime: data.expiredTime, // 时间戳,单位秒,如:1580000000 // // ScopeLimit: true, // 细粒度控制权限需要设为 true,会限制密钥只在相同请求时重复使用
// // ScopeLimit: true, // 细粒度控制权限需要设为 true,会限制密钥只在相同请求时重复使用 // })
// }) // }
// } // xhr.send()
// xhr.send() // // xhr.send(JSON.stringify(options.Scope))
// // xhr.send(JSON.stringify(options.Scope)) // },
// }, // })
// }) },
}, methods: {
methods: { upload() {
upload() { if (this.cosConfig.fileObject == 'tencentOss') {
this.loading = true this.tencentFn()
let file = undefined } else {
if (!this.multiple || this.limit == 1) { this.aliOss()
file = this.file }
} else { },
// 多选上传是多次调用单传的 aliOss() {
file = this.file.shift() this.loading = true
} let file = undefined
let date = new Date() if (!this.multiple || this.limit == 1) {
let format = file.name.match(/\.(\w+)$/g) file = this.file
format = format && format[0] } else {
const params = { // 多选上传是多次调用单传的
Bucket: this.cosConfig.bucketName /* 填入您自己的存储桶,必须字段 */, file = this.file.shift()
Region: this.cosConfig.region /* 存储桶所在地域,例如ap-beijing,必须字段 */, }
Key: `/${dateFormat(date, 'yyyy-MM-dd')}/t${date.getTime()}-${uuid()}${format}`, let date = new Date()
/* 存储在桶里的对象键(例如1.jpg,a/b/test.txt),必须字段。*/ let format = file.name.match(/\.(\w+)$/g)
// 此处使用的格式: /日期/t时间戳-uid-文件后缀名 format = format && format[0]
} // 实例可能未初始化完成
if (!this.ossObj) {
// 实例可能未初始化完成 this.$message.error('存储空间正忙,请稍后再试')
if (!this.cosInstance) { return
this.$message.error('存储空间正忙,请稍后再试') }
return let name = `/${dateFormat(date, 'yyyy-MM-dd')}/t${date.getTime()}-${uuid()}${format}`
} this.ossObj
.multipartUpload(name, file, {
progress: (progressData) => {
console.log(progressData)
this.percentage = progressData.percent * 100
this.speed = (progressData.speed / 1024 / 1024).toFixed(2)
}
})
.then((err1, data) => {
this.percentage = this.speed = 0
if (err1) {
this.loading = false
this.$message.error('上传失败,请稍后再试')
} else {
let location = 'https://' + data.Location
this.$emit('upSuccess', location)
this.type == 2
? //获取视频第一帧画面
getVideoPic({ url: location }).then((res) => {
this.loading = false
this.$emit('getPicUrl', res.data.url)
})
: (this.loading = false)
this.cosInstance.uploadFile( // 使用本地链接提供预览,避免上传后下载的问题
{ let url = window.URL.createObjectURL(file)
...params,
Body: file /* 必须,上传文件对象,可以是input[type="file"]的file对象 */,
onProgress: (progressData) => {
this.percentage = progressData.percent * 100
this.speed = (progressData.speed / 1024 / 1024).toFixed(2)
// this.onProgress && this.onProgress(this.percentage, this.speed)
},
},
(err1, data) => {
this.percentage = this.speed = 0
if (err1) { let name = file.name
this.loading = false if (!this.multiple) {
this.$message.error('上传失败,请稍后再试') this.fileUrlWatch = url
} else { this.$emit('update:fileUrl', location)
let location = 'https://' + data.Location this.$emit('update:fileName', (this.fileNameWatch = name))
this.$emit('upSuccess',location) } else {
this.type == 2 this.fileListWatch = this.fileListWatch.concat({ name, url })
? //获取视频第一帧画面 this.$emit('update:fileList', this.fileList.concat({ name, url: location }))
getVideoPic({ url: location }).then((res) => { }
this.loading = false }
this.$emit('getPicUrl', res.data.url) })
}) .catch((err) => {
: (this.loading = false) console.log(err)
})
},
tencentFn() {
this.loading = true
let file = undefined
if (!this.multiple || this.limit == 1) {
file = this.file
} else {
// 多选上传是多次调用单传的
file = this.file.shift()
}
let date = new Date()
let format = file.name.match(/\.(\w+)$/g)
format = format && format[0]
const params = {
Bucket: this.cosConfig.bucketName /* 填入您自己的存储桶,必须字段 */,
Region: this.cosConfig.region /* 存储桶所在地域,例如ap-beijing,必须字段 */,
Key: `/${dateFormat(date, 'yyyy-MM-dd')}/t${date.getTime()}-${uuid()}${format}`
/* 存储在桶里的对象键(例如1.jpg,a/b/test.txt),必须字段。*/
// 此处使用的格式: /日期/t时间戳-uid-文件后缀名
}
// 使用本地链接提供预览,避免上传后下载的问题 // 实例可能未初始化完成
let url = window.URL.createObjectURL(file) if (!this.cosInstance) {
this.$message.error('存储空间正忙,请稍后再试')
return
}
let name = file.name this.cosInstance.uploadFile(
if (!this.multiple) { {
this.fileUrlWatch = url ...params,
this.$emit('update:fileUrl', location) Body: file /* 必须,上传文件对象,可以是input[type="file"]的file对象 */,
this.$emit('update:fileName', (this.fileNameWatch = name)) onProgress: (progressData) => {
this.percentage = progressData.percent * 100
this.speed = (progressData.speed / 1024 / 1024).toFixed(2)
// this.onProgress && this.onProgress(this.percentage, this.speed)
}
},
(err1, data) => {
this.percentage = this.speed = 0
console.log(data)
if (err1) {
this.loading = false
this.$message.error('上传失败,请稍后再试')
} else { } else {
this.fileListWatch = this.fileListWatch.concat({ name, url }) let location = 'https://' + data.Location
this.$emit('update:fileList', this.fileList.concat({ name, url: location })) this.$emit('upSuccess', location)
this.type == 2
? //获取视频第一帧画面
getVideoPic({ url: location }).then((res) => {
this.loading = false
this.$emit('getPicUrl', res.data.url)
})
: (this.loading = false)
// 使用本地链接提供预览,避免上传后下载的问题
let url = window.URL.createObjectURL(file)
let name = file.name
if (!this.multiple) {
this.fileUrlWatch = url
this.$emit('update:fileUrl', location)
this.$emit('update:fileName', (this.fileNameWatch = name))
} else {
this.fileListWatch = this.fileListWatch.concat({ name, url })
this.$emit('update:fileList', this.fileList.concat({ name, url: location }))
}
} }
} }
}, )
) },
}, remove(i) {
remove(i) { this.$confirm('确定要删除吗?', '提示', {
this.$confirm('确定要删除吗?', '提示', { confirmButtonText: '确定',
confirmButtonText: '确定', cancelButtonText: '取消',
cancelButtonText: '取消', type: 'warning'
type: 'warning', }).then(() => {
}).then(() => { let clone = JSON.parse(JSON.stringify(this.fileList))
let clone = JSON.parse(JSON.stringify(this.fileList)) this.fileListWatch.splice(i, 1)
this.fileListWatch.splice(i, 1) clone.splice(i, 1)
clone.splice(i, 1) this.$emit('update:fileList', clone)
this.$emit('update:fileList', clone) })
}) },
}, handleExceed(file, fileList) {
handleExceed(file, fileList) { this.$message.error('最多上传' + this.limit + '张')
this.$message.error('最多上传' + this.limit + '张') this.loading = false
this.loading = false },
}, async handleBeforeUpload(file, filelist) {
async handleBeforeUpload(file, filelist) { this.loading = true
this.loading = true let isFormat = true
let isFormat = true let isSize = true
let isSize = true
// type: 0 图片(image)、1 语音(voice)、2 视频(video),3 普通文件(file) // type: 0 图片(image)、1 语音(voice)、2 视频(video),3 普通文件(file)
// 统一校验文件后缀名格式 // 统一校验文件后缀名格式
// 如果没有显示配置 format 格式限制,则使用默认下面校验 // 如果没有显示配置 format 格式限制,则使用默认下面校验
let format = this.format let format = this.format
let tip = '' let tip = ''
if (!format || !format.length) { if (!format || !format.length) {
let formatDefault = { let formatDefault = {
0: { tip: 'png/jpg', value: ['png', 'jpg', 'jpeg'] }, 0: { tip: 'png/jpg', value: ['png', 'jpg', 'jpeg'] },
1: { value: ['amr'] }, 1: { value: ['amr'] },
2: { value: ['mp4'] }, 2: { value: ['mp4'] },
3: { tip: 'word/pdf/ppt', value: ['doc', 'docx', 'pdf', 'ppt', 'pptx', 'pps', 'pptsx'] }, 3: { tip: 'word/pdf/ppt', value: ['doc', 'docx', 'pdf', 'ppt', 'pptx', 'pps', 'pptsx'] }
}
format = formatDefault[this.type].value
tip = formatDefault[this.type].tip
}
let match = file.name.match(/\.(\w+)$/g)
let fileFormat = match && match[0].replace('.', '').toLowerCase()
isFormat = format[0] === '*' || format.includes(fileFormat)
if (!isFormat) {
this.$message.error('文件格式错误,仅支持 ' + (tip || format.join(',')) + ' 格式!')
this.loading = false
return Promise.reject()
} }
format = formatDefault[this.type].value
tip = formatDefault[this.type].tip
}
let match = file.name.match(/\.(\w+)$/g)
let fileFormat = match && match[0].replace('.', '').toLowerCase()
isFormat = format[0] === '*' || format.includes(fileFormat)
if (!isFormat) {
this.$message.error('文件格式错误,仅支持 ' + (tip || format.join(',')) + ' 格式!')
this.loading = false
return Promise.reject()
}
// 统一校验文件体积 // 统一校验文件体积
// 如果没有显式配置 maxSize 限制大小,则使用下面默认值,单位 MB, // 如果没有显式配置 maxSize 限制大小,则使用下面默认值,单位 MB,
let maxSize = this.maxSize let maxSize = this.maxSize
if (!maxSize) { if (!maxSize) {
let maxSizeDefault = { 0: 2, 1: 2, 2: 100, 3: 50 } let maxSizeDefault = { 0: 2, 1: 2, 2: 100, 3: 50 }
maxSize || (maxSize = maxSizeDefault[this.type]) maxSize || (maxSize = maxSizeDefault[this.type])
} }
isSize = file.size / 1024 / 1024 < maxSize isSize = file.size / 1024 / 1024 < maxSize
if (!isSize) { if (!isSize) {
this.$message.error('上传文件大小不能超过 ' + maxSize + 'MB!') this.$message.error('上传文件大小不能超过 ' + maxSize + 'MB!')
this.loading = false this.loading = false
return Promise.reject() return Promise.reject()
} }
// 各类型独有的校验 // 各类型独有的校验
let validate = true let validate = true
if (this.type === '0') { if (this.type === '0') {
// 图片 // 图片
let maxImgPx = this.maxImgPx let maxImgPx = this.maxImgPx
if (maxImgPx) { if (maxImgPx) {
try { try {
await new Promise((resolve) => { await new Promise((resolve) => {
let width, height let width, height
let image = new Image() let image = new Image()
//加载图片获取图片真实宽度和高度 //加载图片获取图片真实宽度和高度
image.onload = () => { image.onload = () => {
width = image.width width = image.width
height = image.height height = image.height
if (width > maxImgPx[0]) { if (width > maxImgPx[0]) {
validate = false validate = false
this.$message.error(`图片“宽”度超过${maxImgPx[0]}像素,请重新选择`) this.$message.error(`图片“宽”度超过${maxImgPx[0]}像素,请重新选择`)
} else if (height > maxImgPx[1]) { } else if (height > maxImgPx[1]) {
this.$message.error(`图片“高”度超过${maxImgPx[1]}像素,请重新选择`) this.$message.error(`图片“高”度超过${maxImgPx[1]}像素,请重新选择`)
validate = false validate = false
}
window.URL && window.URL.revokeObjectURL(image.src)
resolve()
} }
window.URL && window.URL.revokeObjectURL(image.src) if (window.URL) {
resolve() let url = window.URL.createObjectURL(file)
} image.src = url
if (window.URL) { } else if (window.FileReader) {
let url = window.URL.createObjectURL(file) let reader = new FileReader()
image.src = url reader.onload = function (e) {
} else if (window.FileReader) { let data = e.target.result
let reader = new FileReader() image.src = data
reader.onload = function (e) { }
let data = e.target.result reader.readAsDataURL(file)
image.src = data
} }
reader.readAsDataURL(file) })
} } catch (e) {
}) console.error(e)
} catch (e) { }
console.error(e)
} }
} } else if (this.type === '1') {
} else if (this.type === '1') { // 语音
// 语音 let amr = new BenzAMRRecorder()
let amr = new BenzAMRRecorder() try {
try { await amr.initWithBlob(file)
await amr.initWithBlob(file) validate = amr.getDuration() <= 60
validate = amr.getDuration() <= 60 if (!validate) {
if (!validate) { this.$message.error('上传文件时长不能超过 60秒!')
this.$message.error('上传文件时长不能超过 60秒!') }
} catch (error) {
console.log(error)
this.$message.error('文件已损坏')
} }
} catch (error) { } else if (this.type === '2') {
console.log(error) // 视频
this.$message.error('文件已损坏') let result = await this.checkVideoCode(file)
if (result.mime.indexOf('video/mp4') === -1) {
this.$message.error('mp4 格式不正确, 请使用标准编码视频!')
this.loading = false
return Promise.reject()
}
} else if (this.type === '3') {
// 普通文件
} }
} else if (this.type === '2') { if (!validate) {
// 视频
let result = await this.checkVideoCode(file)
if (result.mime.indexOf('video/mp4') === -1) {
this.$message.error('mp4 格式不正确, 请使用标准编码视频!')
this.loading = false this.loading = false
return Promise.reject()
} }
} else if (this.type === '3') { // if (beforeUpload) {
// 普通文件 // return beforeUpload(file)
} // }
if (!validate) { if (!this.multiple || this.limit == 1) {
this.loading = false this.file = file
} } else {
// if (beforeUpload) { Array.isArray(this.file) || (this.file = []) // 多选
// return beforeUpload(file) this.file.push(file)
// }
if (!this.multiple || this.limit == 1) {
this.file = file
} else {
Array.isArray(this.file) || (this.file = []) // 多选
this.file.push(file)
}
return validate || Promise.reject()
},
onError(err, file, fileList) {
this.loading = false
this.$message.error('上传文件失败')
},
checkVideoCode(file) {
return new Promise((resolve, reject) => {
const mp4boxFile = MP4Box.createFile()
const reader = new FileReader()
reader.readAsArrayBuffer(file)
reader.onload = function (e) {
const arrayBuffer = e.target.result
arrayBuffer.fileStart = 0
mp4boxFile.appendBuffer(arrayBuffer)
} }
mp4boxFile.onReady = function (info) { return validate || Promise.reject()
resolve(info) },
} onError(err, file, fileList) {
mp4boxFile.onError = function (info) { this.loading = false
reject(info) this.$message.error('上传文件失败')
} },
}) checkVideoCode(file) {
}, return new Promise((resolve, reject) => {
showView(index) { const mp4boxFile = MP4Box.createFile()
let imager = index !== undefined ? this.$refs.image[index] : this.$refs.image const reader = new FileReader()
imager.clickHandler() reader.readAsArrayBuffer(file)
this.$nextTick(() => { reader.onload = function (e) {
// 为遮罩层添加关闭事件 const arrayBuffer = e.target.result
let maskEl = imager.$children[0].$refs['el-image-viewer__wrapper'].firstChild arrayBuffer.fileStart = 0
maskEl.addEventListener('click', () => { mp4boxFile.appendBuffer(arrayBuffer)
event.stopPropagation() }
imager.closeViewer() mp4boxFile.onReady = function (info) {
resolve(info)
}
mp4boxFile.onError = function (info) {
reject(info)
}
}) })
}) },
// this.$refs.image.$refs.closeViewer(); showView(index) {
}, let imager = index !== undefined ? this.$refs.image[index] : this.$refs.image
}, imager.clickHandler()
} this.$nextTick(() => {
// 为遮罩层添加关闭事件
let maskEl = imager.$children[0].$refs['el-image-viewer__wrapper'].firstChild
maskEl.addEventListener('click', () => {
event.stopPropagation()
imager.closeViewer()
})
})
// this.$refs.image.$refs.closeViewer();
}
}
}
</script> </script>
<template> <template>
...@@ -428,7 +512,8 @@ export default { ...@@ -428,7 +512,8 @@ export default {
:src="item.url" :src="item.url"
fit="contain" fit="contain"
:preview-src-list="fileListWatch.map((e) => e.url)" :preview-src-list="fileListWatch.map((e) => e.url)"
alt="" /> alt=""
/>
<div class="action-mask"> <div class="action-mask">
<i class="el-icon-search mr5" @click="showView(index)"></i> <i class="el-icon-search mr5" @click="showView(index)"></i>
<!-- <span v-if="action.includes('download')" @click="download(item)"> <!-- <span v-if="action.includes('download')" @click="download(item)">
...@@ -456,7 +541,8 @@ export default { ...@@ -456,7 +541,8 @@ export default {
:limit="limit" :limit="limit"
:on-error="onError" :on-error="onError"
:on-exceed="handleExceed" :on-exceed="handleExceed"
:before-upload="handleBeforeUpload"> :before-upload="handleBeforeUpload"
>
<!-- <!--
element-loading-text="正在上传..." element-loading-text="正在上传..."
:on-success="onSuccess" :on-success="onSuccess"
...@@ -474,7 +560,7 @@ export default { ...@@ -474,7 +560,7 @@ export default {
<circle cx="50" cy="50" r="20" fill="none" class="path"></circle> <circle cx="50" cy="50" r="20" fill="none" class="path"></circle>
</svg> </svg>
</div> </div>
<div class="cc" style="margin-top: 35px"> <div class="cc" style="margin-top: 35px;">
{{ speed + 'M/s' }} {{ speed + 'M/s' }}
</div> </div>
</div> </div>
...@@ -488,7 +574,8 @@ export default { ...@@ -488,7 +574,8 @@ export default {
:src="fileUrlWatch" :src="fileUrlWatch"
class="upload-img upload-img-single uploader-size" class="upload-img upload-img-single uploader-size"
:preview-src-list="[fileUrlWatch]" :preview-src-list="[fileUrlWatch]"
fit="contain" /> fit="contain"
/>
<div class="action-mask" @click.self.stop> <div class="action-mask" @click.self.stop>
<i class="el-icon-search" @click.prevent.stop="showView()"></i> <i class="el-icon-search" @click.prevent.stop="showView()"></i>
...@@ -512,10 +599,11 @@ export default { ...@@ -512,10 +599,11 @@ export default {
playsinline="true" playsinline="true"
:autoplay="false" :autoplay="false"
:key="fileUrlWatch" :key="fileUrlWatch"
preload="auto"> preload="auto"
>
<source :src="fileUrlWatch" type="video/mp4" /> <source :src="fileUrlWatch" type="video/mp4" />
</video> </video>
<div class="action-mask" style="height: 30%" @click.self.stop> <div class="action-mask" style="height: 30%;" @click.self.stop>
<i class="el-icon-edit"></i> <i class="el-icon-edit"></i>
</div> </div>
</template> </template>
...@@ -524,7 +612,7 @@ export default { ...@@ -524,7 +612,7 @@ export default {
<i class="el-icon-edit ml10"></i> <i class="el-icon-edit ml10"></i>
<!-- a链接用本地视频打不开,视频地址使用远程地址 --> <!-- a链接用本地视频打不开,视频地址使用远程地址 -->
<a @click.stop :href="/\.mp4$/.test(fileNameWatch) ? fileUrl : fileUrlWatch" target="_blank"> <a @click.stop :href="/\.mp4$/.test(fileNameWatch) ? fileUrl : fileUrlWatch" target="_blank">
<i class="el-icon-view ml10" style="vertical-align: middle"></i> <i class="el-icon-view ml10" style="vertical-align: middle;"></i>
</a> </a>
</template> </template>
</div> </div>
...@@ -540,100 +628,100 @@ export default { ...@@ -540,100 +628,100 @@ export default {
</template> </template>
<style lang="scss" scoped> <style lang="scss" scoped>
::v-deep.uploader { ::v-deep.uploader {
display: inline-block; display: inline-block;
vertical-align: middle; vertical-align: middle;
.el-upload { .el-upload {
display: block; display: block;
border-radius: 6px; border-radius: 6px;
cursor: pointer; cursor: pointer;
position: relative;
overflow: hidden;
}
}
// 默认组件大小,如需修改,请通过外部重写该类样式
.uploader-size {
width: 178px;
height: 178px;
}
.upload-action {
position: relative; position: relative;
text-align: center;
}
.uploader-icon {
display: flex;
font-size: 28px;
align-items: center;
justify-content: center;
color: #8c939d;
border-radius: 6px;
border: 1px dashed #d9d9d9;
transition: all 0.3s;
&:hover {
border-color: var(--color);
color: var(--color);
}
}
.progress {
overflow: hidden; overflow: hidden;
} }
} .upload-img-single {
// 默认组件大小,如需修改,请通过外部重写该类样式 border: 1px dashed #eee;
.uploader-size { }
width: 178px; .upload-img {
height: 178px; display: block;
}
.upload-action {
position: relative;
text-align: center;
}
.uploader-icon {
display: flex;
font-size: 28px;
align-items: center;
justify-content: center;
color: #8c939d;
border-radius: 6px;
border: 1px dashed #d9d9d9;
transition: all 0.3s;
&:hover {
border-color: var(--color);
color: var(--color);
} }
} .upload-video {
.progress { display: block;
overflow: hidden; width: 300px;
} height: 150px;
.upload-img-single { box-sizing: border-box;
border: 1px dashed #eee; color: #fff;
} background-color: #000;
.upload-img { position: relative;
display: block; padding: 0;
} font-size: 10px;
.upload-video { line-height: 1;
display: block; font-weight: normal;
width: 300px; font-style: normal;
height: 150px; word-break: initial;
box-sizing: border-box; }
color: #fff; .tip {
background-color: #000; margin-top: 10px;
position: relative; color: #aaa;
padding: 0; font-size: 12px;
font-size: 10px; }
line-height: 1; .img-item {
font-weight: normal; position: relative;
font-style: normal; display: inline-block;
word-break: initial; vertical-align: middle;
} margin: 0 10px 10px 0;
.tip { transition: all 0.3s;
margin-top: 10px; }
color: #aaa; .action-mask {
font-size: 12px; position: absolute;
} display: flex;
.img-item { justify-content: space-around;
position: relative; align-items: center;
display: inline-block; padding: 0 30px;
vertical-align: middle; width: 100%;
margin: 0 10px 10px 0; height: 100%;
transition: all 0.3s; left: 0;
} top: 0;
.action-mask { cursor: pointer;
position: absolute; text-align: center;
display: flex; color: #fff;
justify-content: space-around; opacity: 0;
align-items: center; font-size: 20px;
padding: 0 30px; transition: opacity 0.3s;
width: 100%; background-color: rgba(0, 0, 0, 0.5);
height: 100%; z-index: 1;
left: 0; }
top: 0; .upload-item {
cursor: pointer; &:hover {
text-align: center; .action-mask {
color: #fff; opacity: 1;
opacity: 0; }
font-size: 20px;
transition: opacity 0.3s;
background-color: rgba(0, 0, 0, 0.5);
z-index: 1;
}
.upload-item {
&:hover {
.action-mask {
opacity: 1;
} }
} }
}
</style> </style>
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!