跨域報錯的原因 最開始上傳視頻成功後,video標簽的src會直接引入上傳後的服務端資源地址,然後使用canvas截圖就發生了跨域報錯的提示。 Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not ...
跨域報錯的原因
最開始上傳視頻成功後,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>