zoukankan      html  css  js  c++  java
  • js实现base64转换

    有三种方式

    1.第一种是使用jquery的base64.js,在https://github.com/beatgammit/base64-js 上下载base64.js

    使用如下命令对数据进行base64的编码与解码:

    加密使用:Base64.encode(con);

    解密使用:Base64.decode(con);

    案例如下:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="javascripts/base64.js"></script>
    <script src="javascripts/jquery.min.js"></script>
    </head>
    <body>
    <input type="text" class="content">
    <button onclick='submit()'>加密</button>
    <button onclick="showtext()">解密</button>
    <script>
    var encodeStr = '';
    function submit() {
    let con = document.querySelector('.content').value;
    encodeStr= Base64.encode(con);
    console.log(encodeStr);
    $.ajax({
    method: 'GET',
    url: '/test',
    data: {
    title:encodeStr
    },
    success:function(res) {
    console.log(res)
    }
    })
    }
    
    // 解密
    function showtext() {
    var decodeStr = Base64.decode(encodeStr);
    console.log(decodeStr);
    }
     
    </script>
    </body>
    </html>

    2.使用js自带的转为base64的方法:

    js中内置的base64编码和解码。

    var encodedData = window.btoa("Hello, world"); // 编码
    var decodedData = window.atob(encodedData); // 解码

    兼容性IE10以上和其他浏览器都支持,还是相对不错的,要是移动端都支持。

    借两张 MDN的图片,要是真遇到IE怎么办,引入polyfill库,引入第三方库,或者直接不进行编码。

    3.node中自带的base64编码与解码方法

    node中自带的base64的编码与解码分为三种:普通字符串/十六进制/图片

    (1)普通字符串

    //编码
    new Buffer(String).toString('base64');
    
    //解码
    new Buffer(base64Str, 'base64').toString();
    (2)十六进制Hex
    //编码
    new Buffer(String, 'base64').toString('hex');
    
    //解码
    new Buffer(base64Str, 'hex').toString('utf8');
    (3)图片
    const fs = require('fs');
    //编码
    function base64_encode(file) {
        let bitmap = fs.readFileSync(file);
        return new Buffer(bitmap).toString('base64');
    }
    
    //解码
    function base64_decode(base64str, file) {
        var bitmap = new Buffer(base64str, 'base64');
        fs.writeFileSync(file, bitmap);
    }
  • 相关阅读:
    Linux 查看dns运行状态
    Linux 查看网卡流量、网络端口
    Linux 查看磁盘读写速度IO使用情况
    Linux 查看系统状态
    Linux 查看进程
    Python RabbitMQ RPC实现
    [转]轻量级 Java Web 框架架构设计
    java集合总结【转】
    java 线程
    Geoserver基本使用、WMS服务发布与OpenLayers测试
  • 原文地址:https://www.cnblogs.com/lxz123/p/12883751.html
Copyright © 2011-2022 走看看