vue 文件转base64方法 && base64转blob路径方法 && a链接下载文件 && form表单下载文件

24 篇文章 0 订阅
本文介绍了如何使用Vue实现文件转Base64的功能,包括使用FileReader读取文件并转换为Base64字符串,以及如何将Base64编码的图片下载为Blob并通过a链接、form表单和下载事件进行下载。重点展示了编码和下载过程的代码示例。
摘要由CSDN通过智能技术生成

vue 文件转base64:

      getBase64(file) {
        return new Promise((resolve, reject) => {
          let reader = new FileReader();
          let fileResult = "";
          reader.readAsDataURL(file);
          reader.onload = () => {
            fileResult = reader.result;
          };
          reader.onerror = (error) => {
            reject(error);
          };
          reader.onloadend = () => {
            resolve(fileResult);
          };
        });
      }
调用方法:
this.getBase64(file).then(res=>{
     this.imgBase64 = res;
 });

base64转blob路径并下载:

savePicture = (base64, fileName = "下载文件(测试).pdf") => {
  var arr = base64.split(",");
  var bytes = atob(arr[1]);
  let ab = new ArrayBuffer(bytes.length);
  let ia = new Uint8Array(ab);
  for (let i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i);
  }
  var blob = new Blob([ab], { type: "application/octet-stream" });
  var url = URL.createObjectURL(blob);
  const el = document.createElement("a");
  el.style.display = "none";
  el.setAttribute("target", "_blank");
  fileName && el.setAttribute("download", fileName);
  el.href = url;
  document.body.appendChild(el);
  el.click();
  document.body.removeChild(el);
};
调用方法:
this.savePicture("data:application/pdf;base64," + flie.base64);

a链接下载方式

downloadEvt(url, fileName = "下载文件.PDF") => {
  const el = document.createElement("a");
  el.style.display = "none";
  el.setAttribute("target", "_blank");
  fileName && el.setAttribute("download", fileName);
  el.href = url;
  document.body.appendChild(el);
  el.click();
  document.body.removeChild(el);
};
调用方法:
this.downloadEvt(https://care-dev.oss-cn-hangzhou.aliyuncs.com/v2_care/salesproject/3114/test-248.pdf);

form表单下载方式

downloadform(url) {
  var form = document.createElement("form");
  form.action = url;
  form.method = "get";
  form.style.display = "none";
  document.body.appendChild(form);
  form.submit();
  document.body.removeChild(form);
};
调用方法:
this.downloadform(https://care-dev.oss-cn-hangzhou.aliyuncs.com/v2_care/salesproject/3114/test-248.pdf);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值