javascript
// 获取视频基本信息
const getVideoBasicInfo = (videoSrc) => {
return new Promise((resolve, reject) => {
const video = document.createElement("video");
video.src = videoSrc;
// 视频一定要添加预加载
video.preload = "auto";
// 视频一定要同源或者必须允许跨域
video.crossOrigin = "Anonymous";
// 监听:异常
video.addEventListener("error", (error) => {
reject(error);
});
// 监听:加载完成基本信息,设置要播放的时常
video.addEventListener("loadedmetadata", () => {
const videoInfo = {
video,
width: video.videoWidth,
height: video.videoHeight,
duration: video.duration,
};
resolve(videoInfo);
});
});
};
javascript
// 将获取到的视频信息,转化为图片地址
const getVideoPosterInfo = (videoInfo) => {
return new Promise((resolve) => {
const { video, width, height } = videoInfo;
video.addEventListener("canplay", () => {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
ctx.drawImage(video, 0, 0, width, height);
const posterUrl = canvas.toDataURL("image/jpg");
resolve({ posterUrl });
});
});
};
此函数就是最终可以拿到图片地址的函数了。
javascript
//获取处理后的图片地址
const getImgUrl = async (videoSrc) => {
let videoInfo = await getVideoBasicInfo(videoSrc);
let {posterUrl} = await getVideoPosterInfo(videoInfo);
return posterUrl
};
拓展:
如果还需要将拿到的图片进行上传到远程服务器的处理 例如阿里云或者OSS服务器中则看下面代码继续处理
javascript
//base64转file 文件
const base64ToFile = (data) => {
// 将base64 的图片转换成file对象上传 atob将ascii码解析成binary数据
let binary = atob(data.split(",")[1]);
let mime = data.split(",")[0].match(/:(.*?);/)[1];
let array = [];
for (let i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
let fileData = new Blob([new Uint8Array(array)], {
type: mime,
});
let file = new File([fileData], `${new Date().getTime()}.png`, {
type: mime,
});
return file;
}
最终上传工具就写完了。 实际调用 只需要传递 视频地址即可。
javascript
//获取OSS地址
const uploadImgUrl = async(videoSrc)=>{
let imgUrl = await getImgUrl(videoSrc)
let fileList= base64ToFile(imgUrl)
var formData = new FormData()
formData.set('filename', fileList)
formData.set('merchantId', localStorage.getItem('MerchantId'))
formData.set('Directory', 'Image')
return new Promise((resolve, reject) => {
axios.post(`${configs.host.test}/api/FileUpload/Upload`, formData)
.then(res => {
resolve(res.data);
})
});
}
export {
uploadImgUrl
}