【uniapp】获取上传视频的md5,适用于APP和H5
代码实现
APP端使用 uni.getFileInfo()
即可
H5环境需要安装spark-md5
npm install spark-md5
封装的获取上传视频的md5方法
import SparkMD5 from 'spark-md5'
/**
* 用于获取视频的md5
* @param {Object} e 要上传的文件
* @param {Object} digestAlgorithm 取值 md5、sha1
*/
export function getFileInfo(e, digestAlgorithm = 'md5') {
return new Promise((resolve, reject) => {
// #ifdef APP
uni.getFileInfo({
filePath: e.tempFilePath,
digestAlgorithm,
success(res) {
resolve(res)
},
fail(err) {
console.log(`获取文件信息失败,返回空对象`)
resolve({
size: '',
digest: null
})
}
})
// #endif
// #ifdef H5
try {
let fileReader = new FileReader()
let Spark = new SparkMD5.ArrayBuffer()
fileReader.readAsArrayBuffer(e.tempFile)
fileReader.onload = function (res) {
Spark.append(res.target.result)
let md5 = Spark.end()
resolve({
size: '',
digest: md5
})
}
} catch (error) {
console.log('🚀 ~ 获取视频的md5 ~ error:', error)
resolve({
size: '',
digest: null
})
}
// #endif
})
}
上传视频方法
/**
* 选取视频
* @param {Object} event 选取的视频本地信息,包含路径等信息
*/
async afterReadVideo(e) {
if (JSON.stringify(e) === '{}' || !e) {
return
}
let self = this
let videoDuration = e.duration
let sizeMb = Number(e.size) / 1024 / 1024
if (sizeMb > 1536) {
return uni.showToast({
title: '视频过大,不得超过1.5G',
icon: 'none',
duration: 1500
})
}
// 视频是否截图完的flag
self.uploadImgFinished = false
self.uploadLoading = true
let videoUrl = ''
try {
// 上传视频
videoUrl = await uploadFile(e.tempFilePath, self.processingProgress)
self.currVideoUrl = videoUrl
self.videoImgUrl = videoUrl + '!/snapshot/point/00:00:00/format/png'
// 获取视频的md5
let fileInfo = await getFileInfo(e)
self.videoMd5 = fileInfo.digest
self.uploadLoading = false
// 视频是否截图完的flag
self.uploadImgFinished = true
this.videoDuration = videoDuration
} catch (err) {
// 上传失败
this.videoDuration = 0
let msg = '上传失败,请稍后重试'
if (self.uploadLoading) {
msg = '上传已取消'
}
self.uploadLoading = false
self.downloadTask = null
uni.showToast({
title: msg,
icon: 'none'
})
}
}