Explain Codes LogoExplain Codes Logo

How to download a file in React JS

javascript
cors-proxy
axios
file-download
Anton ShumikhinbyAnton ShumikhinΒ·Feb 17, 2025
⚑TLDR

To prompt a file download rapidly in React, you'll need a function that generates an anchor element (<a>) attached to a blob URL. Here's a boiled-down snippet of the magic trick:

const downloadFile = (fileData, fileName, mimeType) => { /* * When life gives you fileData, make a file! πŸ‹ --> πŸ“ƒ */ const blob = new Blob([fileData], { type: mimeType }); const link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = fileName; // Like calling a pet, it won't come unless you call it by its name document.body.appendChild(link); link.click(); // Poke it and run! document.body.removeChild(link); // Clean up after your mess };

Use downloadFile() along with the file's data, desired filename, and MIME type to initiate the download. Simplicity and efficiency at its finest!

Cross-origin resource sharing (CORS)

In a more adventurous landscape, such as downloads from various domains, you might need to tackle CORS. A CORS proxy can handle this, or you could tweak your server's access control settings.

Backend-as-savior

Either establishing your own server endpoint or hosting a CORS proxy server can help overcome frontend download constraints. However, be aware of the potential security implications. And oh! Make sure the server sets accurate headers (Content-Type, Content-Disposition) for reliable downloads.

Handling binary files

For stubborn binary files such as images or PDFs, libraries like Axios are handy. Setting the responseType to 'blob' helps correctly parse the binary data, sort of like speaking their language!

Dealing with different file types

For specific file types, such as stubborn-as-a-mule Excel documents, an appropriate plugin or library like js-file-download could come to your rescue for a more navigable React file downloading process.

Advanced downloading techniques

Introduction React's state and lifecycle methods into the picture, you can manage the download state, provide user feedback or handle errors during download attempts for an improved user experience.

Gulping down some good file organization practices, keeping your salient files within the app's "public" folder works great for easy access and link creation.

References