As I am not able to add comments so posting as answer. I have tried the same thing and posted the question for same in this link.

For post method i get the success with fetch as below.

 fetch("url",
        { 
            method: "POST",
            headers: { "Content-Type": "application/json",'Authorization': 'Bearer ' + window.localStorage["Access_Token"]},
            body:data
        }).then(response => response.blob()).then(response => ...*your code for download*... )

You are getting corrupted file because you are not receiving content as blob or arraybuffer.

Answer from Sandeep Rasgotra on Stack Overflow
🌐
Medium
medium.com › @khushbooverma8319 › download-api-file-in-frontend-91bd51e4ee19
Download file in frontend getting from API | by Khushbooverma | Medium
May 22, 2023 - Suppose we have a button on click of which we want to download the CSV file. We have a onClick handler named handlDownload as shown below. const handleDownload = () => { setLoading(true); API.get('https://sample/api', { responseType: "blob", }) .then((response) => { const url = window.URL.createObjectURL(new Blob([response.data])); console.log(url); var blob = new Blob([response.data], { type: "text/plain;charset=utf-8", }); saveAs(blob, `${response.fileName}.pdf`); setLoading(false); }) .catch((err) => { console.log(err); setLoading(false); }); };
Discussions

How to download a file using ReactJS with Axios in the frontend and FastAPI in the backend?
Below is a fully working example on how to create and download a file (Document), using either Axios or Fetch API in the frontend. This answer utilizes methods and code excerpts from this and this answer, as well as the answers here and here. Plesase refer to the above answers for more details on the methods used below. For demo purposes, the below example uses Jinja2Templates, but, in a similar way, you can use the scripts below in your ReactJS ... More on stackoverflow.com
🌐 stackoverflow.com
Downloading files retrieved via API
Goal: Trying to download files pulled from an API, but they keep downloading corrupt Steps: utils.downloadFile(DownloadFile2.data, 'test', 'pdf') - have tried adding {base64Binary: } have tried modifying the API headers a few ways. Currently using content type: application/octet-stream and ... More on community.retool.com
🌐 community.retool.com
0
0
July 18, 2024
How to download a file from an api in react
0 React and Axios download a file from Node JS server · 1 Downloading a file from a Node.JS API REST (express) with React.JS (Axios Get) More on stackoverflow.com
🌐 stackoverflow.com
Download file from Node Express server to React
In my React component, I have a button to download a file. When clicked, it authenticates on the server that the user is the file owner. Upon… More on reddit.com
🌐 r/node
1
6
April 11, 2019
People also ask

What is the best way to handle file downloads in React?
The most efficient way to handle file downloads in React is using an API. This allows files to be downloaded directly on the client side.
🌐
blog.filestack.com
blog.filestack.com › home › react download file from api: a guide
React download file from API: A Guide
What security considerations should you consider when downloading files from an external API?
Regarding security, you should validate file size, format, and type. Moreover, you must implement authorization and authentication techniques.
🌐
blog.filestack.com
blog.filestack.com › home › react download file from api: a guide
React download file from API: A Guide
How do I download a file with a specific MIME type?
Pass the MIME type as the second argument to the Blob constructor. For JSON use text/json, for CSV use text/csv, for plain text use text/plain.
🌐
theroadtoenterprise.com
theroadtoenterprise.com › home › blog › how to export and download csv and json files in react
How to Export and Download CSV and JSON Files in React | The Road ...
🌐
JavaScript in Plain English
javascript.plainenglish.io › download-pdf-from-api-in-reactjs-using-axios-and-blobs-699be8a27ca7
Download PDF from API in React (Using Axios and blobs) | by Subhanu | JavaScript in Plain English
December 11, 2024 - ... Now we have the file data, we can proceed to handle the API response and trigger the file download. When it comes to handling the API response for file downloading in ReactJS, we need to access the file data and create a blob URL from it.
🌐
Filestack
blog.filestack.com › home › react download file from api: a guide
React download file from API: A Guide
July 19, 2023 - With this method, we first get the file data via the API, then interpret it, and finally download it on the client side without the need to open a new tab. We can download various file types using an API, such as PDF, PNG, CSV, and ZIP. When it comes to React download files from API, we have multiple options.
🌐
Svar
docs.svar.dev › api › actions › download-file
download-file | React filemanager Documentation
You can do it via the api.intercept() method. The next example shows how to configure the downloading of a file. About loading data from the server see here: Loading data · import { useState, useEffect } from "react"; import { Filemanager } from "@svar-ui/react-filemanager"; const server = ...
🌐
Theroadtoenterprise
theroadtoenterprise.com › home › blog › how to export and download csv and json files in react
How to Export and Download CSV and JSON Files in React | The Road To Enterprise
1 month ago - To download a file in React, create a Blob from your data, generate an object URL with URL.createObjectURL, attach it to a temporary <a> element, and programmatically click it. No libraries needed.
Find elsewhere
🌐
DEV Community
dev.to › farisdurrani › how-to-download-a-file-in-a-full-stack-react-app-2jkk
How to download a file in a full-stack React app - DEV Community
July 23, 2023 - See A simple React Next + Node app in Typescript. First, install axios in frontend/. We're using axios instead of the native fetch to post the file since we want to print the download progress. ... In frontend/src/app/page.tsx, let's create a very basic file download button with its functionalities: "use client"; import { useEffect, useState } from "react"; import axios from "axios"; import download from "downloadjs"; export default function Home() { async function handleDownloadFile() { const filename = "a.json"; const res = await axios.get( "http://localhost:8000/downloadFile?"
🌐
Tech Prescient
techprescient.com › home › blogs › react custom hook typescript to download a file through api
React File Download Hook – Secure API with TypeScript
October 3, 2021 - Build a secure, reusable file download hook in React with TypeScript. Handle blobs, auth headers, and user states using Axios and custom hooks for clean UX.
🌐
GeeksforGeeks
geeksforgeeks.org › reactjs › how-to-download-pdf-file-in-reactjs
How To Download PDF file in ReactJS? - GeeksforGeeks
The fetch() method allows you to fetch PDF files from a server or URL and download them dynamically. Unlike the anchor tag approach, this method fetches the file asynchronously and provides more flexibility, especially if the file is hosted ...
Published   July 23, 2025
🌐
GitHub
github.com › codingwithmanny › reactfiledownloader
GitHub - codingwithmanny/reactfiledownloader: Simple React frontend that achieves downloading files on the client side from the backend API
Simple React frontend that achieves downloading files on the client side from the backend API - codingwithmanny/reactfiledownloader
Starred by 4 users
Forked by 3 users
Languages   JavaScript 85.8% | HTML 14.2% | JavaScript 85.8% | HTML 14.2%
Top answer
1 of 1
5

In the Axios GET request, you have to make sure the responseType parameter is set to blob. Once you get the response from the API, you will need to pass the Blob object (i.e., response.data) to the URL.createObjectURL() function. Below is a fully working example on how to create and download a file (Document), using either Axios or Fetch API in the frontend. This answer utilizes methods and code excerpts from this and this answer, as well as the answers here and here. Plesase refer to the above answers for more details on the methods used below. For demo purposes, the below example uses Jinja2Templates, but, in a similar way, you can use the scripts below in your ReactJS app.

app.py

from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from fastapi.responses import FileResponse
from docx import Document

app = FastAPI()
templates = Jinja2Templates(directory="templates")


@app.get('/')
def main(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})
    
@app.post("/create")
def create_file():
    document = Document()
    document.add_heading("file generated", level=1)
    document.add_paragraph("test")
    document.save('generated_file.docx')
    return {"status":"Done!"}
    
@app.get("/download")
def download_generated_file():
    file_path = "generated_file.docx"
    return FileResponse(file_path, media_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document', filename=file_path)

Using Axios

tempaltes/index.htnl

<!DOCTYPE html>
<html>
   <head>
      <title>Create and Download a Document</title>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js"></script>
   </head>
   <body>
      <input type="button" value="Create Document" onclick="createFile()">
      <div id="response"></div><br>
      <input type="button" value="Download Document " onclick="downloadFile()">
      <script>
         function createFile() {
            axios.post('/create', {
                  headers: {
                     'Accept': 'application/json',
                     'Content-Type': 'application/json'
                  }
               })
               .then(response => {
                  document.getElementById("response").innerHTML = JSON.stringify(response.data);
               })
               .catch(error => {
                  console.error(error);
               });
         }
         
         function downloadFile() {
            axios.get('/download', {
                  responseType: 'blob'
               })
               .then(response => {
                  const disposition = response.headers['content-disposition'];
                  filename = disposition.split(/;(.+)/)[1].split(/=(.+)/)[1];
                  if (filename.toLowerCase().startsWith("utf-8''"))
                     filename = decodeURIComponent(filename.replace("utf-8''", ''));
                  else
                     filename = filename.replace(/['"]/g, '');
                  return response.data;
               })
               .then(blob => {
                  var url = window.URL.createObjectURL(blob);
                  var a = document.createElement('a');
                  a.href = url;
                  a.download = filename;
                  document.body.appendChild(a); // append the element to the dom
                  a.click();
                  a.remove(); // afterwards, remove the element  
               })
               .catch(error => {
                  console.error(error);
               });
         }
      </script>
   </body>
</html>

Using Fetch API

tempaltes/index.htnl

<!DOCTYPE html>
<html>
   <head>
      <title>Create and Download a Document</title>
   </head>
   <body>
      <input type="button" value="Create Document" onclick="createFile()">
      <div id="response"></div><br>
      <input type="button" value="Download Document" onclick="downloadFile()">
      <script>
         function createFile() {
            fetch('/create', {
                  method: 'POST',
                  headers: {
                     'Accept': 'application/json',
                     'Content-Type': 'application/json'
                  }
               })
               .then(response => response.text())
               .then(data => {
                  document.getElementById("response").innerHTML = data;
               })
               .catch(error => {
                  console.error(error);
               });
         }
         
         function downloadFile() {
            fetch('/download')
               .then(response => {
                  const disposition = response.headers.get('Content-Disposition');
                  filename = disposition.split(/;(.+)/)[1].split(/=(.+)/)[1];
                  if (filename.toLowerCase().startsWith("utf-8''"))
                     filename = decodeURIComponent(filename.replace("utf-8''", ''));
                  else
                     filename = filename.replace(/['"]/g, '');
                  return response.blob();
               })
               .then(blob => {
                  var url = window.URL.createObjectURL(blob);
                  var a = document.createElement('a');
                  a.href = url;
                  a.download = filename;
                  document.body.appendChild(a); // append the element to the dom
                  a.click();
                  a.remove(); // afterwards, remove the element
               })
               .catch(error => {
                  console.error(error);
               });
         }
      </script>
   </body>
</html>
🌐
The Daily Coder
blog.mellisdesigns.com › react-authenticated-file-downloads
Authenticated File Downloads in React
September 18, 2019 - <AuthenticatedLink url='/protected/api/documents/filename.png' filename='filename.pdf' > Download file now </AuthenticatedLink> We check that the a element does not have a href attribute assigned to stop the recursive pattern that could happen when simulating a click and calling the click handler again. Using Reacts.createRef allows us to manage the element with ease.
🌐
Expo Documentation
docs.expo.dev › expo sdk › filesystem
FileSystem - Expo Documentation
expo-file-system provides access to files and directories stored on a device or bundled as assets into the native project. It also allows downloading files from the network. ... If you are installing this in an existing React Native app, make ...
🌐
Retool
community.retool.com › 💬 app building
Downloading files retrieved via API - 💬 App Building - Retool Forum
July 18, 2024 - Goal: Trying to download files pulled from an API, but they keep downloading corrupt Steps: utils.downloadFile(DownloadFile2.data, 'test', 'pdf') - have tried adding {base64Binary: } have tried modifying the API headers a few ways. Currently using content type: application/octet-stream and using this transform const base64Message = "data:application/pdf;base64" + btoa(unescape(encodeURIComponent(data.message))) return base64Message; That seems to get good base64, but the download stay...
🌐
JavaScript in Plain English
javascript.plainenglish.io › how-to-download-files-on-button-click-reactjs-f7257e55a26b
How to Create a Download Button Using React | JavaScript in Plain English
July 16, 2024 - // file object const file = new Blob(texts, {type: 'text/plain'});// anchor link const element = document.createElement("a"); element.href = URL.createObjectURL(file); element.download = "100ideas-" + Date.now() + ".txt";// simulate link click document.body.appendChild(element); // Required for this to work in FireFox element.click(); } ... The file blob doesn't add a newline to the texts automatically. You can use [texts.join('\n')] to add a new line · 💡 Note: If you’re facing re-rending issues in your React project, useState in your custom hooks might be the reason.
🌐
React
react.dev
React
React is also an architecture. Frameworks that implement it let you fetch data in asynchronous components that run on the server or even during the build. Read data from a file or a database, and pass it down to your interactive components.
🌐
CodeSandbox
codesandbox.io › s › fetch-based-file-download-0kxod
fetch based file download - CodeSandbox
January 29, 2020 - fetch based file download by johnculviner using react, react-dom, react-scripts
Published   Jun 30, 2019
Author   johnculviner
🌐
AWS Amplify
docs.amplify.aws › react-native › build-a-backend › storage › download-files
Download files - React Native - AWS Amplify Gen 2 Documentation
React Native · Flutter · Android · Swift · Edit on GitHub · Was this page helpful? Yes · No · Can you provide more details? File an issue on GitHub · Page updated Jul 4, 2025 · To further customize your in-app experience, you can use the getUrl or downloadData API from the Amplify Library for Storage.
🌐
Hashnode
belindamarionk.hashnode.dev › how-to-export-csv-and-json-data-from-api-in-react
How to export CSV and JSON data from API in React
February 14, 2023 - import axios from 'axios'; // Function to export data as a file const exportData = (data, fileName, type) => { // Create a link and download the file const blob = new Blob([data], { type }); const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = fileName; a.click(); window.URL.revokeObjectURL(url); }; // Fetch data from API endpoint axios.get('/api/data') .then(response => { // Convert data to JSON format const jsonData = JSON.stringify(response.data); exportData(jsonData, "data.json", 'application/json'); }) .catch(error => { // Handle errors console.error(error); });