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.
Use atob
see quick example
let myData = "YQ=="
console.log(atob(myData)); // a
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With