4

I have an application that renders a file on the server side. I am passing it as "base64" string through json. I need to decode and download a file on the client side. I have presented the code in a simplified form, leaving what is relevant to the question.

Here is the route on the express server:

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 component on the client:

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;

Regards.

Kiten
  • 985
  • 2
  • 17
  • 35

2 Answers2

1

Use atob

see quick example

let myData = "YQ=="


console.log(atob(myData)); // a
GMKHussain
  • 3,342
  • 1
  • 21
  • 19
1

This helped me do decode and download xlsx file:

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;

I used download.js

Kiten
  • 985
  • 2
  • 17
  • 35