Vue图片URL转File实践[已解决跨域问题]

async imgToFile(url) {
      const self = this
      const image = new Image()
      //let url = "https://shenjianblog.oss-cn-shanghai.aliyuncs.com/pic/20220612/sfxs.jpg"
      // 使用 fetch 获取图像作为 Blob 对象
      const response = await fetch(url.replace("https://shenjianblog.oss-cn-shanghai.aliyuncs.com", "/imgApi"));
      const blob = await response.blob();
      const imgSrc = URL.createObjectURL(blob)
      // 加载 Blob 对象的 URL
      image.src = imgSrc;
      image.onload = () => {
        const canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        const context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height);
        canvas.toBlob(function (blob) {
          const selectedFile = new File([blob], 'image.png', {type: 'image/png'});
	  console.log(selectedFile)
        })
      };
    },

在Vue.config.js中配置代理即可

  // 配置代理
  devServer:{
    open: true,
    proxy:{
      "/imgApi": {
        target: 'https://shenjianblog.oss-cn-shanghai.aliyuncs.com',
        changeOrigin: true,
        pathRewrite:{
          '^/imgApi':''   //请求的时候使用这个api就可以
        }
      }
    }
  }

你可能感兴趣的:(干货,vue.js,前端,javascript)