前端Base64 编码和解码的使用方法

使用 Base64 类从 ‘js-base64’ 库进行 Base64 编码和解码

一、安装 ‘js-base64’库

vue: 使用 npm 或 yarn 包管理器来安装‘js-base64’ 库

npm install --save js-base64

原生: 通过

<script src="https://cdn.jsdelivr.net/npm/[email protected]/base64.min.js"></script>

二、导入‘js-base64’库

vue:
导入 Base64 类:

import {
    
     Base64 } from 'js-base64';

或者:

import {
    
     encode, decode } from 'js-base64';

三、在页面中使用

vue:
Base64 编码的使用示例:

import {
    
     Base64 } from 'js-base64';

const stringToEncode = 'Hello, World!'; // 要进行 Base64 编码的字符串
const encodedString = Base64.encode(stringToEncode); // 进行 Base64 编码
console.log(encodedString); // 输出:SGVsbG8sIFdvcmxkIQ==

Base64 解码的使用示例:

import {
    
     Base64 } from 'js-base64';

const base64String = 'SGVsbG8sIFdvcmxkIQ=='; // Base64 编码的字符串
const decodedString = Base64.decode(base64String); // 进行 Base64 解码
console.log(decodedString); // 输出:Hello, World!

或者,导入 encode 和 decode 函数:
Base64 编码的使用示例:

import {
    
     encode } from 'js-base64';

const stringToEncode = 'Hello, World!'; // 要进行 Base64 编码的字符串
const encodedString = encode(stringToEncode); // 进行 Base64 编码
console.log(encodedString); // 输出:SGVsbG8sIFdvcmxkIQ==

Base64 解码的使用示例:

import {
    
     decode } from 'js-base64';

const base64String = 'SGVsbG8sIFdvcmxkIQ=='; // Base64 编码的字符串
const decodedString = decode(base64String); // 进行 Base64 解码
console.log(decodedString); // 输出:Hello, World!

原生:
使用 ‘js-base64’ 进行 Base64 编码和解码:

<!DOCTYPE html>
<html>
<head>
  <title>Base64 Example</title>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/base64.min.js"></script>
</head>
<body>
  <script>
    const stringToEncode = 'Hello, World!'; // 要进行 Base64 编码的字符串
    const encodedString = Base64.encode(stringToEncode); // 进行 Base64 编码
    console.log(encodedString); // 输出:SGVsbG8sIFdvcmxkIQ==

    const base64String = 'SGVsbG8sIFdvcmxkIQ=='; // Base64 编码的字符串
    const decodedString = Base64.decode(base64String); // 进行 Base64 解码
    console.log(decodedString); // 输出:Hello, World!
  </script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/m0_47791238/article/details/132274295