现取前端base64转csv和csv转base64

环境:
1:上传: 将要上传的文件转为base64编码,然后将base64编码发送给后端
2:下载: 将后端返回的base64编码转为文件并且下载


此处用于csv文件,封装的一个js文件可直接复制使用,并且解决了下载时乱码和下载后为空文件的问题。

let keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
let Base64 = {

  encodeFuc: function (input) {
    let output = "",
      chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
    input = utf8_encode(input);
    while (i < input.length) {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);
      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;
      if (isNaN(chr2)) {
        enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
        enc4 = 64;
      }
      output = output +
        keyStr.charAt(enc1) + keyStr.charAt(enc2) +
        keyStr.charAt(enc3) + keyStr.charAt(enc4);
    }
    return output;
  },
  utf8_encode: function (string) {
    string = string.replace(/\r\n/g, "\n");
    let utftext = "";
    for (let n = 0; n < string.length; n++) {
      let c = string.charCodeAt(n);
      if (c < 128) {
        utftext += String.fromCharCode(c);
      } else if ((c > 127) && (c < 2048)) {
        utftext += String.fromCharCode((c >> 6) | 192);
        utftext += String.fromCharCode((c & 63) | 128);
      } else {
        utftext += String.fromCharCode((c >> 12) | 224);
        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
        utftext += String.fromCharCode((c & 63) | 128);
      }

    }
    return utftext;
  },
  decodeFuc: function (input) {
    let output = "",
      chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
    while (i < input.length) {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));
      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;
      output = output + String.fromCharCode(chr1);
      if (enc3 != 64) {
        output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
        output = output + String.fromCharCode(chr3);
      }
    }
    output = this.utf8_decode(output);
    return output;
  },
  utf8_decode: function (utftext) {
    let string = "",
      i = 0,
      c = 0,
      c1 = 0,
      c2 = 0,
      c3 = 0;
    while (i < utftext.length) {
      c = utftext.charCodeAt(i);
      if (c < 128) {
        string += String.fromCharCode(c);
        i++;
      } else if ((c > 191) && (c < 224)) {
        c2 = utftext.charCodeAt(i + 1);
        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
        i += 2;
      } else {
        c2 = utftext.charCodeAt(i + 1);
        c3 = utftext.charCodeAt(i + 2);
        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
        i += 3;
      }
    }
    return string;
  }
}
class csvUtils {
  static exportCsv(res, fileName) {
    let decodedata = Base64.decodeFuc(res);
    //encodeURIComponent解决中文乱码
    let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(decodedata);
    //通过创建a标签实现
    let link = document.createElement("a");
    link.href = uri;
    //对下载的文件命名
    link.download = fileName + ".csv";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  static importCsv(file) {
    return new Promise((resolve, reject) => {
      let reader = new FileReader();
      let fileResult = "";
      reader.readAsDataURL(file.raw);
      reader.onload = () => {
        fileResult = reader.result;
      };
      reader.onerror = (error) => {
        reject(error);
      };
      reader.onloadend = () => {
        resolve(fileResult);
      };
    });
  }
}
export default csvUtils


引入

1:文件转base64

这里的上传,我是用我自己写的,不是用的封装的js文件

let that = this
if (window.FileReader) {
    let reader = new FileReader();
    reader.readAsDataURL(this.file.raw);
    reader.onload = function (e) {
    let arr = e.target.result.split(",");
    let base64 = arr[1].slice('4')  // 这行代码是为了去掉 77u/ 这个占位符的,可根据你的情况使用
     就得到了上传文件的base64编码,把 base64  传递给后端即可
      ps: 这里要用that,this指向不是window
    };
 }

封装的js文件导入的上传也是只需要调用的时候传入文件就行了

2:base64转文件

import csvUtils from "@/api/csvUtils";  // 引入的上面封装js代码
csvUtils.exportCsv('base64编码',‘文件名字’);  // 使用
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在VB6中将文件换为Base64可以使用以下代码: ```vb Function FileToBase64(filePath As String) As String Dim stream As Object Set stream = CreateObject("ADODB.Stream") stream.Type = 1 ' Binary stream.Open stream.LoadFromFile filePath Dim bytes() As Byte bytes = stream.Read Dim base64String As String base64String = EncodeBase64(bytes) FileToBase64 = base64String End Function Function EncodeBase64(bytes() As Byte) As String Dim dom As Object Set dom = CreateObject("MSXML2.DOMDocument") Dim elem As Object Set elem = dom.createElement("tmp") elem.DataType = "bin.base64" elem.nodeTypedValue = bytes EncodeBase64 = Replace(elem.Text, vbLf, "") End Function ``` 使用上述代码,你可以将文件路径作为参数传递给`FileToBase64`函数,它将返回文件的Base64字符串表示。请确保在使用之前将`MSXML2`库添加到你的项目引用中。 #### 引用[.reference_title] - *1* *3* [java:文件base64,支持图片和doc/csv/pdf等常用文件](https://blog.csdn.net/qiaodaima0/article/details/107047424)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [input file 文件base64](https://blog.csdn.net/liwan09/article/details/109689903)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值