如何在客户端从JSON响应中解码Base64文件?

4

我有一个在服务器端渲染文件的应用程序,我将其作为“base64”字符串通过json传递。我需要在客户端解码并下载文件。

这里是express服务器上的路由:

let xlsx = require('node-xlsx').default;
const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
  const data = [[1, 2, 3], ['a', 'b', 'c']];
  var buffer = xlsx.build([{ name: "mySheetName", data: data }])
    .toString('base64');
  res.json(buffer);
});

module.exports = router;

在客户端上的React组件:

import React, { useEffect } from 'react';
import axios from 'axios';

const First = () => {
  useEffect(() => {
    axios({
      url: 'http://localhost:5000/excel',
      method: 'GET',
      responseType: 'blob',
    }).then(res => {
      const url = window.URL.createObjectURL(new Blob([res.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', 'data.xlsx');
      document.body.appendChild(link);
      link.click();
    });
  }, []);
  return (
    <div>
      <h3>First page</h3>
      <hr className="gold" />
    </div>
  );
};

export default First;

敬启者。

2个回答

1
使用 atob
快速示例:

let myData = "YQ=="


console.log(atob(myData)); // a


如果输出是一个字节,那么这将产生奇怪的输出。 - FastDeveloper

1
这帮助我解码并下载xlsx文件:
import React, { useEffect } from 'react';
import axios from 'axios';
import download from 'downloadjs';

const First = () => {
  useEffect(() => {
    axios.get('http://localhost:5000/excel')
      .then(res => {
        download(atob(res.data), 'data.xlsx', { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
      });
  }, []);
  return (
    <div>
      <h3>First page</h3>
      <hr className="gold" />
    </div>
  );
};

export default First;

我使用了download.js


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接