Get File Name From FileStreamResult When Using Ajax/Axios?

5.9k views Asked by At

I have in my asp.net core api controller

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

I am doing an ajax request to get this file

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

then I am using a library called download which takes 3 parameters with one of them being "filename" and I am wondering if I can somehow get the filename that is coming from the server.

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

Cors

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

There are 1 answers

11
Alexander On

First you need to expose Content-Disposition header in your CORS configuration since it's not included in CORS-safelisted response headers

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

Then you should be able to parse response Content-Disposition header and get file name from it

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);
    });