Excel File Download in React with Auth Headers and Mock Testing
Content
React implementation for downloading binary Excel data from an authenticated API endpoint, with support for mock data during development/testing.
This snippet assumes the backend endpoint returns the binary data from the file.
Key Points
- Uses fetch API with Authorization header
- Handles binary data as Blob
- Creates temporary download link
- Includes environment flag toggle for mock data
Code Example
function ExcelDownloadButton({ useMock = false }) {
const handleDownload = async () => {
try {
let blob;
let fileName = 'downloaded-file.xlsx';
if (useMock) {
// Mock implementation
blob = mockExcelData();
} else {
// Real API call with auth
const response = await fetch('https://api.example.com/excel', {
method: 'GET',
headers: {
'Authorization': 'Bearer token-here',
},
});
if (!response.ok) throw new Error(`Error: ${response.status}`);
blob = await response.blob();
// Extract filename if available
const contentDisposition = response.headers.get('Content-Disposition');
if (contentDisposition) {
fileName = extractFilenameFromHeader(contentDisposition);
}
}
// Create and trigger download
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
} catch (error) {
console.error('Download failed:', error);
}
};
return <button onClick={handleDownload}>Download Excel</button>;
}
Connections
- React-Blob-Handling
- API-Authentication-Patterns
- Frontend-Testing-Strategies
- Binary-File-Downloads
- React Javascript Framework
References
- React Documentation
- Fetch API MDN
- File API MDN
Sources:
- From: Version1