0

I'm returning an Excel file (which works fine) as octet stream from C# API using FileContentResult(byte[], MediaTypeNames.Application.Octet, "file.xlsx"

and then I'd want to open download file prompt from js and everything works fine except that the file is corrupted

I've been trying various solutions from these posts and Excel file always result in being corrupted

JavaScript: Create and save file

JavaScript blob filename without link

Create binary blob in JS

and also FileSaver.js

$.ajax({
url: url,
type: 'POST',
data: formData,
processData: false,
contentType: 'application/json',
success: function (result) 
{
    saveFile(result);
}
});

I know that file is working fine because when I'm testing it via Swagger then it works fine

Any ideas?

Joelty
  • 1,751
  • 5
  • 22
  • 64

2 Answers2

0

Workaround:

Returning base64 of that file and create a element on that page with href attribute that has value of

data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,

and then add your base64 to that value, so

'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,'+base64

and then perform .click() on that link

Conversion of Base64 Encoded into XSLX

You can specify name of file by using download="" attribute

Joelty
  • 1,751
  • 5
  • 22
  • 64
0

What worked for me is adding responseType: 'arraybuffer' to the ajax:

$.ajax({
  url: url,
  type: 'POST',
  data: formData,
  contentType: false,
  processData: false,
  xhrFields: {
    responseType: 'arraybuffer'
  },
  success: function (data) {
    const blob = new Blob([data]);
    saveAs(blob, "output.xlsx");
  }
});
Gerhard Powell
  • 5,965
  • 5
  • 48
  • 59