SoFunction
Updated on 2025-04-14

Some common methods of how to return file streams from the backend when downloading files in front-end

On the front end, processing file downloads usually involves accepting oneFile Stream(Blob or ArrayBuffer) and convert it into a link that can be downloaded. Here are some common ways to implement front-end file downloads and accept file streams.

1. Create a download link using blob and

Assume that the backend returns a file stream (for exampleBlob), you can create a file download link in the front end by following the steps below.

Example: Create a file download using Blob

// Suppose you get the file stream (Blob) from the backendfetch('/path/to/your/file')
  .then(response => ())  // Get file stream (Blob)  .then(blob => {
    // Create a temporary URL to point to this blob    const url = (blob);

    // Create a download link    const link = ('a');
     = url;
     = ''; // Set the name of the download file
    // Simulation click to download    ();

    // Release URL object    (url);
  })
  .catch(error => {
    ('File download failed:', error);
  });

2. Process ArrayBuffer type file streams through FileReader

If the backend returnsArrayBuffer(binary file data), you can useFileReaderConvert it toBlobObject, then download.

Example: ProcessingArrayBufferFile Stream

fetch('/path/to/your/file')
  .then(response => ())  // Get file stream (ArrayBuffer)  .then(arrayBuffer => {
    // Convert ArrayBuffer to Blob    const blob = new Blob([arrayBuffer]);

    // Create a temporary URL to point to this blob    const url = (blob);

    // Create a download link    const link = ('a');
     = url;
     = ''; // Set the name of the download file
    // Simulation click to download    ();

    // Release URL object    (url);
  })
  .catch(error => {
    ('File download failed:', error);
  });

3. Use axios and responseType: 'blob' to process file downloads

If you are usingaxiosTo make a request, you can set itresponseTypeforblobto receive file streams. This is a common way to deal with file stream downloads.

Example: Use axios to process file stream downloads

import axios from 'axios';

('/path/to/your/file', { responseType: 'blob' })
  .then(response => {
    const blob = ;

    // Create a temporary URL to point to this blob    const url = (blob);

    // Create a download link    const link = ('a');
     = url;
     = ''; // Set the name of the download file
    // Simulation click to download    ();

    // Release URL object    (url);
  })
  .catch(error => {
    ('File download failed:', error);
  });

4. Handle downloads with Content-Disposition

In some cases, the backend will send withContent-DispositionThe response of the HTTP header, which means that the file should be downloaded as an attachment. In this case, you usually don't need to do anything special, the browser will automatically handle the download of the file, but you can still force the download through JavaScript.

Example: Forced file download using axios

axios({
  url: '/path/to/your/file',
  method: 'GET',
  responseType: 'blob', // Request file stream})
  .then(response => {
    const blob = ;

    // Get the file name, usually from the response header    const contentDisposition = ['content-disposition'];
    const filename = contentDisposition
      ? ('filename=')[1].replace(/"/g, '')
      : 'default_filename.ext';

    // Create a temporary URL to point to this blob    const url = (blob);

    // Create a download link    const link = ('a');
     = url;
     = filename; // Set the name of the download file
    // Simulation click to download    ();

    // Release URL object    (url);
  })
  .catch(error => {
    ('File download failed:', error);
  });

5. Error handling and file flow timeout

When downloading files, you also need to consider error handling and timeout settings:

fetch('/path/to/your/file', { timeout: 5000 })  // Set the timeout to 5 seconds  .then(response => {
    if (!) {
      throw new Error('Network response was not ok');
    }
    return ();
  })
  .then(blob => {
    // Process Blob file streams and download    const url = (blob);
    const link = ('a');
     = url;
     = '';
    ();
    (url);
  })
  .catch(error => {
    ('File download failed:', error);
  });

Summarize

  • Blob file stream:passBlobandIt is easy to download file streams.
  • ArrayBuffer File Stream: Can be passedArrayBufferConvert toBlobDownload it later.
  • Axios Download: By settingresponseType: 'blob', can be usedaxiosProcess file stream download.
  • Content-Disposition: Certain responses may passContent-DispositionThe header forces the file to download, you can extract the file name and download the file based on this header.

Using these methods, you can easily implement the front-end accepting file streams and providing file download functions. If the backend returns a large file, make sure to perform appropriate error handling, timeout settings, etc. to improve the user experience.

This is the article about some common methods of how to return file streaming when downloading files on the front-end. For more related front-end downloading files on the back-end, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!