需求
需要在上传视频时获取到视频第一帧的图片并上传到远程服务器上
过程
1、获取第一帧图片
getIMg = (file)=>{
//file参数传入的是视频文件流
const video = document.createElement("video");
video.setAttribute('crossorign', 'anonymous');
video.setAttribute('controls', 'controls');
video.setAttribute('autoplay', 'autoplay');
// 这样就不用处理跨域问题了
video.volume = 0;
video.setAttribute('src', window.URL.createObjectURL(file));
video.setAttribute('width', 400);
video.setAttribute('height', 240);
video.addEventListener('loadeddata', () => {
// 创建canvas画布
const canvas = document.createElement('canvas');
canvas.width = video.width; // 设置画布的长宽也就是图片的长宽
canvas.height = video.height;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
const img = document.createElement('img');
img.src = canvas.toDataURL('image/png');
//上传方法
this.dataURLtoFile(img.src,"videoPic.png");
})
}
2、上传获取到的第一帧图片
dataURLtoFile = (file,filename)=>{
const arr = file.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);
}
const newfile = new File([u8arr], filename, {type: mime});
//获取到图片文件流 调用上传到远程服务器的方法
const {dispatch} = this.props
const {uploadHeaders} = this.props
dispatch({
type:"VideoPic/upload",
payload:{files:newfile},
headers:uploadHeaders,
callback:(res)=>{
// console.log("上传视频第一帧",res)
if(res.result==="1"){
this.setState({videoShot:res.path})
}else{
message.error("上传视频第一帧出错",res.msg)
}
}
})
}