RTK Query – download files from .NET API with authentication

by admin
Download files from .NET api

Learn how to download files from a protected .NET api endpoint. When developing applications, downloading files is often required on various parts of the application. Think of downloading an Excel file with data in a table, or a generated PDF by the API. I assume that you have a .NET API with file endpoints that return a File().

You don’t want to expose these files to the public, therefore they are protected like any other endpoint in your API. This article will show you how to download these files, like you may call any other endpoint.

Required packages beside Redux toolkit:

yarn add file-saver

In our example, we use a base RTK query handler that handles various things for us, such as the Bearer authentication. Refer to to this article for more details.

Setup

So, let’s add a new Slice to put our file download API call in. I called it TestFileSlice.ts.

import { apiGenerator } from 'src/redux/api/apiGenerator'

const generatedAPI = apiGenerator.injectEndpoints({
  endpoints: builder => ({
    downloadTestFile: builder.mutation<any, number>({
      query: body => ({
        url: `/v1/Testfile`,
        method: 'POST',
        body: body,
        responseHandler: response => response.blob()
      })
    })
  }),
  overrideExisting: true
})

export const { useDownloadTestFileMutation } = generatedAPI

As you can see we have added a responseHandler to the API call, that returns a blob.

Download file

Now that we have added the call to the endpoint, lets use it.

import saveAs from 'file-saver'
import { useDownloadTestFileMutation } from 'src/slices/RegistrationSlice'

const DownloadComponent = () => {
  const [downloadTestFile] = useDownloadTestFileMutation()

  const handleDownloadFile = async (input: number) => {
    await downloadTestFile(input)
      .unwrap()
      .then(payload => {
        saveAs(payload, 'TestFile.xlsx')
      })
  }

  return <button onClick={() => handleDownloadFile(1)}>Download file</button>
}

export default DownloadComponent

In the code above you can see that we import the downloadTestFileMutation, then call it and convert the payload to a file download with the file-saver libary.

Related Posts

1 comment

Cyril July 15, 2024 - 5:43 am

Thank you ! That helped me a lot

Reply

Leave a Comment