React Download [2021] File Rename -
In React applications, downloading a file with a custom name requires more than just an anchor tag if the file is served from a different origin or needs a dynamic name generated on the client. Browsers typically use the download attribute of an tag to rename files, but this is often ignored for cross-origin URLs.
To reliably rename a file during download in React, you must fetch the file data as a , create a local object URL, and then trigger the download programmatically. Method 1: Using Fetch API (Native) react download file rename
The Fetch API is the most straightforward way to handle this without external dependencies. You fetch the data, convert it to a Blob, and use a temporary anchor element to trigger the download. javascript In React applications, downloading a file with a
const downloadAndRename = async (url, newName) => { try { const response = await fetch(url); const blob = await response.blob(); const blobUrl = window.URL.createObjectURL(blob); const link = document.createElement('a'); link.href = blobUrl; link.download = newName; // This sets the new filename document.body.appendChild(link); link.click(); // Cleanup document.body.removeChild(link); window.URL.revokeObjectURL(blobUrl); } catch (error) { console.error("Download failed:", error); } }; Use code with caution. Method 2: Using Axios Method 1: Using Fetch API (Native) The Fetch
If your project already uses Axios, you must specify responseType: 'blob' to prevent Axios from trying to parse the file data as JSON. Javascript rename file on download - Stack Overflow