上傳視頻並截圖,跨域報錯的解決辦法

跨域報錯的緣由

最開始上傳視頻成功後,video標籤的src會直接引入上傳後的服務端資源地址,而後使用canvas截圖就發生了跨域報錯的提示。javascript

Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.java

按網上說的方法設置video標籤的屬性 crossorigin="anonymous",仍是報錯,緣由是服務端的請求頭沒設置,不容許跨域訪問。canvas

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.跨域

解決辦法: 視頻上傳成功後,不要引入線上地址,仍然使用本地視頻地址,便可解決跨域問。ide

完整代碼

<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>
相關文章
相關標籤/搜索