跨域报错的原因
最开始上传视频成功后,video标签的src会直接引入上传后的服务端资源地址,然后使用canvas截图就发生了跨域报错的提示。
Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
按网上说的方法设置video标签的属性 crossorigin="anonymous"
,还是报错,原因是服务端的请求头没设置,不允许跨域访问。
Failed to load http://xxxx.oss-cn-shenzhen.aliyuncs.com/2018/08/22/1749/VU0SL0msslJvN1q3YNN2fmr1E4zmmE0vmHTV7A9s.mp4: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
解决办法: 视频上传成功后,不要引入线上地址,仍然使用本地视频地址,即可解决跨域问。
完整代码
<template>
<div>
<video ref='videoView' crossorigin="anonymous" v-show="videoId" :src="videoPath" controls="controls" class="video-upload-post-preview m-box-center m-box-center-a image-wrap more-image img3"></video>
<input ref='videofile' id="selectvideo" type="file" name="file" @change="uploadVideo" class="upload__input m-rfile">
</div>
</template>
<script>
import sendImage from "@/util/SendImage.js";
export default {
data() {
return {
videoId: "",
videoPath: "",
videoCover: ""
}
},
methods: {
uploadVideo(e) {
let file = e.target.files[0];
sendImage(file)
.then(id => {
// console.log(id)
this.videoId = id
this.videoPath = URL.createObjectURL(file)
setTimeout(() => {
this.captureImage(file);
}, 300);
})
.catch(e => {
this.$Message.error("上传失败,请稍后再试");
});
},
captureImage(file) {
let video = this.$refs.videoView;
// console.log(this.$refs, video)
var canvas = document.createElement("canvas"); //创建一个canvas
canvas.width = video.videoWidth * 0.8; //设置canvas的宽度为视频的宽度
canvas.height = video.videoHeight * 0.8; //设置canvas的高度为视频的高度
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height); //绘制图像
let imgBase64 = canvas.toDataURL()
let imgFile = this.dataToFile(imgBase64)
// console.log('img', imgFile)
sendImage(imgFile)
.then(id => {
this.videoCover = id
})
.catch(e => {
this.$Message.error("上传失败,请稍后再试");
});
},
dataToFile(urlData) {
var bytes = window.atob(urlData.split(',')[1]); //去掉url的头,并转换为byte
//处理异常,将ascii码小于0的转换为大于0
var ab = new ArrayBuffer(bytes.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
return new Blob([ab], {
type: 'image/jpg'
});
}
}
}
</script>