SoFunction
Updated on 2025-04-05

Detailed explanation of how to handle Excel file streams returned from the backend

Purpose:

Click the button on the page to download the excel file

step:

  • Send a request to the backend: useaxios(or other HTTP client) sends a request to the backend to get the file. Usually, files are returned as blobs.

  • Processing response data: Process the response data (Blob object) as a download link and simulate a click to trigger the download.

Specific steps:

1. Install axios (if not installed yet)

npm install axios

2. Write Vue components

<template>
  <div>
    <button @click="downloadExcel">download Excel</button>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  methods: {
    async downloadExcel() {
      try {
        const response = await axios({
          url: '/api/path-to-your-excel-file', // Replace with the actual request URL          method: 'GET',
          responseType: 'blob', // Important: Specify the response type as blob        });

        // Create a new URL object and generate a download link        const url = (new Blob([],
        { type: 'application/' }));
        const link = ('a');
         = url;
        ('download', 'File name.xlsx'); // Set the downloaded file name         = 'none' // Hide elements        (link);
        ();
        
        // Clean up the DOM and release the URL object        (link);
        (url);
      } catch (error) {
        ('An error occurred while downloading the file:', error);
      }
    }
  }
}
</script>

<style scoped>
/* Style code */
</style>

Note 1:

Processing the Excel file stream returned by the backend for download in Vue, you can do it through the following steps:

  •  

    Set the response type of the request‌: When the backend returns the file as a stream file, the frontend needs to set it when requesting itresponseType: 'blob'to ensure that file streams are received and processed correctly. This is because a Blob object can represent a piece of binary data that is used to process binary files, such as Excel files.

  • Create a download link‌: Once the Blob data is received, the download can be triggered by creating a temporary URL. use(blob)Methods can create a temporary URL representing the Blob object and then create a<a>Tags, set themhrefThe property is this temporary URL and setdownloadThe attribute is the expected file name, simulate click this<a>Tags to start downloading.

  • Handle different request methods‌: According to the requirements of the backend interface, the request method may be POST or GET. If it is a POST request, it needs to be set in the request headerresponseType: 'blob'. If it is a GET request, it is usually not necessary to explicitly set the response type, because the default is to get the data‌.

  • Compatibility considerations‌: Although files can be processed and downloaded through the above methods, different browsers and download methods (such as through<a>Tag or) There are different compatibility. For example, by<a>The way tag downloads work well in Firefox and Chrome, but does not support IE and Safari. ByAlthough it is simple to download, it can only make GET requests, and it is inconvenient to use if there is token verification.

  • Things to note‌: When processing streaming files, you need to pay attention to the integrity and correctness of the files. If the file is corrupt, it may be because the correct response type is not set during the request, causing the file to be parsed and opened correctly.

To sum up, handling the Excel file stream returned by the backend in Vue involves correct request settings, creation of temporary URLs, compatibility considerations, and precautions to ensure that the file can be downloaded and used correctly.

Note 2:

typeIt's creatingBlobAn option for object to specifyBlobMIME type of data. MIME type (Multipurpose Internet Mail Extensions type) is a standard way to describe file formats. It helps browsers or other applications understand how to process the file.

In your example:

const blob = new Blob([response], 
{ type: 'application/' });
  • responseIt is your data content (usually the raw data obtained from the server).
  • typeYes, specifiedBlobThe MIME type of the object.

Explain the value of type

  • application/is a MIME type used to identify Microsoft Excel.xlsxFile format.

Why you need to specify a MIME type

  • Browser processing: The browser decides how to handle or display based on the MIME type.Blob. If the MIME type is not specified, the browser may not recognize the file type correctly, which may cause problems during downloading or displaying.

  • File processing: The correct MIME type helps ensure that the file is processed and downloaded in the correct way. For example, when you download an Excel file, specifying the MIME type ensures that the file is correctly recognized as an Excel file.

  • Download and display: If your application needs to handle multiple file formats, specifying the MIME type can ensure that the file is processed and displayed correctly.

Common MIME types

  • Text filetext/plain
  • HTML filestext/html
  • JSON filesapplication/json
  • CSV Filestext/csv
  • Excel Filesapplication/
  • PDF Fileapplication/pdf

CreatingBlobWhen  object, correctly specifying the MIME type is a key step to ensure the correct file processing and download.

Summarize

This is the article about how the front-end handles Excel file stream returned from the back-end. For more related processing of the back-end content of 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!