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就可以
        }
      }
    }
  }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
当使用Vue下载文本文件时,可能会出现跨域问题。这是因为浏览器的安全策略要求在跨域请求时,服务器必须设置Access-Control-Allow-Origin响应头来允许客户端访问资源。 解决方法: 1. 在服务器端设置Access-Control-Allow-Origin响应头来允许跨域访问。 2. 在Vue中使用axios或fetch等工具发送请求时,需要设置withCredentials为true,以便发送跨域请求时能够携带cookies。 3. 将下载文件的请求改为后端处理,前端通过ajax请求后端,后端返回文件流数据,并设置Content-Disposition响应头来提示浏览器下载文件。 代码示例: 1.设置Access-Control-Allow-Origin响应头 ```js // Node.js Express框架示例 app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With'); next(); }); ``` 2.使用axios下载文件 ```js axios.get('/download/file', { responseType: 'blob', withCredentials: true // 携带cookies }).then(res => { const url = window.URL.createObjectURL(new Blob([res.data])) // 创建下载链接 const link = document.createElement('a') link.href = url link.setAttribute('download', 'file.txt') document.body.appendChild(link) link.click() window.URL.revokeObjectURL(url) // 释放资源 }) ``` 3.使用ajax请求后端下载文件 ```js // 后端代码示例(Node.js) router.get('/download/file', function(req, res, next) { const filePath = path.join(__dirname, '../public/file.txt') const fileName = 'file.txt' res.setHeader('Content-Disposition', 'attachment; filename=' + fileName) res.setHeader('Content-Type', 'application/octet-stream') const readStream = fs.createReadStream(filePath) readStream.pipe(res) }) ``` ```js // 前端代码示例 axios({ url: '/download/file', method: 'get', responseType: 'blob', }).then((response) => { const url = window.URL.createObjectURL(new Blob([response.data])) const link = document.createElement('a') link.href = url link.setAttribute('download', 'file.txt') document.body.appendChild(link) link.click() window.URL.revokeObjectURL(url) }) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沈健_算法小生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值