How can I extract the file name from a FileStreamResult when making a request with Ajax or Axios?

Currently, in my asp.net core api controller, I have the following code snippet:

 return new FileStreamResult(excel, "application/ms-excel")
        {
            FileDownloadName = filename
        };

Afterwards, I make an ajax request to fetch this file:

   var response = axios.get(
      `/endpoint`, {
        responseType: 'blob'
      });

Once the response is received, I utilize a library named download. This library requires 3 parameters, one of which is called "filename". Is there a way for me to extract and use the filename provided by the server?

download(response.data,"test.xlsx", content);

Regarding Cors:

 services.AddCors(options => options.AddPolicy("Cors",
       builder =>
       {
           builder.AllowAnyOrigin()
           .AllowAnyMethod()
           .AllowAnyHeader();
       }));

Answer №1

To start, ensure that you configure your CORS settings to expose the Content-Disposition header as it is not automatically included in the list of CORS-safelisted response headers

services.AddCors(options => options.AddPolicy("Cors",
    builder =>
    {
        builder.AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader()
            .WithExposedHeaders("Content-Disposition");
    }));

Once set up, you can then extract the file name from the response's Content-Disposition header

axios.get(
    "/endpoint", {
        responseType: 'blob'
    })
    .then(response => {
        var contentDisposition = response.headers["content-disposition"];
        var match = contentDisposition.match(/filename\s*=\s*"(.+)"/i);
        var filename = match[1];
        console.log(filename);
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing jQuery to load form(s), submit data via POST method, and fetch results without refreshing the

After conducting thorough research, I have been unsuccessful in implementing any of the solutions I have come across. It seems like I am close to a solution, but there may be something crucial that I am missing... A question similar to mine was asked on t ...

Unable to execute multiple queries within a CloudCode query

In my quest to discover new users who I have not connected with before using a cloud function, I am utilizing several tables: Users table - This standard table includes an additional "hasLight" boolean column Connected table: 'user' - a point ...

Troubleshooting why Vue.js isn't updating the DOM with two-way binding

I'm currently utilizing Vue.js for implementing two-way binding. One issue I am facing is with an edit button that should convert a text field into an input field upon clicking. However, the DOM does not update immediately as expected. For instance: ...

What is the best way to pass data from an async whilst function to an express.js res.send() statement?

I am currently utilizing a graph database with the seraph-api library to access it. My issue lies in attempting to perform an asynchronous graph traversal using a breadth-first search. Despite my efforts, the data points of the relationship are not reachin ...

Putting off the execution of jQuery scripts

For my simple website, I incorporated the jScrollPane plugin to create a centered, fixed div with a height of 600px. Everything was functioning smoothly until I added a Facebook comment section, causing the scrollable div not to wait for the comment block ...

Is it possible to refresh the dom without causing any disruptions to the Mouse Cursor?

Consider this function I'm currently utilizing: $('body').html( function(i,html) { var arr = html.split(". "); arr[arr.length-1]="<span class='findme' >"+arr[arr.length-1]+"</span>&nbsp;"; alert(arr) ...

Utilize JSON data from a service to populate a Bootstrap Modal

I need assistance with populating a Modal using the JSON values I received from a service call. The object structure is simple and understandable, like this: var object = [ {Value1: "Val1", Value2: "Val", Value3: [{a:"a",b:"b"}] }] The ajax call looks ...

Is there a way for me to increment the value of 'sessionStorage.fgattempt' whenever either 'fgMade()' or 'threeMade()' are called?

Currently, I am developing a basketball game stat tracker and need to update the field goal attempts every time I make a field goal or three-pointer. Additionally, I am looking for ways to optimize the javascript code provided. The main requirement is to ...

methods for converting an array to JSON using javascript

Our team is currently working on developing a PhoneGap application. We are in the process of extracting data from a CSV file and storing it into a SQLite database using the File API in PhoneGap. function readDataUrl(file) { var reader = new FileReade ...

Performing an AJAX request to a form within a CSS modal

Greetings from France, and please excuse any language errors in my English. I am currently coding in Symfony 3 and have an entity called "book" which can have different attributes (client, student, organizer, and/or speaker) based on the selected "type" a ...

Implementing TypeScript in an Asp.net Core ReactJS application`s configuration

After using Visual Studio 2022 to create an asp.net core Reactjs project, I discovered that everything was written in javascript instead of typescript. Is there a way to switch this project over to typescript? ...

jQuery-powered web application, experiencing compatibility issues when deployed on Windows Server 2003 and Internet Explorer

While developing a web application on XP and FF (with occasional IE checks through IE 8), I encountered an issue when deploying it to a WS 2003 site running IE 7. My jQuery code for dynamically sizing divs does not execute, even when explicitly stating div ...

HTML drag-and-drop setDragImage fails to show ghost image on initial drag operation

Currently, I am working on developing a drag and drop menu feature that allows users to drag an image thumbnail from one div to a canvas element. The main issue I am facing is that the source div uses a sprite for displaying its background thumbnail. As a ...

Retrieve the value of an object without relying on hardcoded index values in TypeScript

I am working with an object structure retrieved from an API response. I need to extract various attributes from the data, which is nested within another object. Can someone assist me in achieving this in a cleaner way without relying on hardcoded indices? ...

I encounter difficulties using my static resources in the root route of my Express.js application

Can you guide me on how to implement styles and images from the assets folder in my webpage, specifically for the root route? As an example, I have a styles.css file located at assets/styles.css. In my code, I am using app.use(express.static('assets&a ...

Convert a fresh Date() to the format: E MMM dd yyyy HH:mm:ss 'GMT'z

The date and time on my website is currently being shown using "new date()". Currently, it appears as: Thu May 17 2018 18:52:26 GMT+0530 (India Standard Time) I would like it to be displayed as: Thu May 17 2018 18:43:42 GMTIST ...

Is there an issue with the initial positioning of the tooltip in the seiyria angular-bootstrap slider?

After implementing the Seiyria angular-bootstrap-slider for a range slider, I encountered an issue where the tooltip is positioned incorrectly upon loading the page. While it functions correctly on a regular page, it appears in the wrong position within a ...

Determining the lowest and highest values for a slider's range

I am looking to extract the minimum and maximum values from a price range. Here is the code snippet for reference: http://jsfiddle.net/dhana36/b453V/2/ Currently, I have one input field that controls both minimum and maximum values. However, I would pref ...

Can someone break down the meaning of "returning $http.post" in Angular while developing a factory service?

I've been grappling with the concept of return $http.post('/some link') and can't seem to fully grasp it. Imagine I have a node/express backend and am utilizing Angular for my frontend. Within my api, there is a function like this: v ...

What is more effective: utilizing document fragments or string concatenation for adding HTML to the DOM?

My task involves adding a collection of cards to the DOM. html <div class="card"> <div class="card-title">Card 1</div> <div class="card-subtext">This is card 1</div> </div> js let ...