欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

上传视频并截图,跨域报错的解决办法

程序员文章站 2022-04-28 21:52:33
跨域报错的原因 最开始上传视频成功后,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>