To fix Excel file download being corrupted in React and Axios, we set the responseType
option when we make our Axios request to 'arrayBuffer'
.
For instance, we write
import React, { Component } from "react";
import { saveAs } from "file-saver";
//...
const C = () => {
const exportIssues = async () => {
const response = await axios.get("/issues/export", {
responseType: "arraybuffer",
});
const blob = new Blob([response.data], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});
saveAs(blob, "file.xlsx");
};
//...
};
to create the exportIssues
function that calls axios.get
with the URL for the Excel file.
We set the responseType
to 'arraybuffer'
to download the file as a binary file.
And then we transform the response.data
response data to a Blob
with the Blob
constructor.
And then we call saveAs
with the returned blob
and the file name for the file.