How to open file with window.open in a post?

1

My controller returns two file types: pdf and excel.

return File(stream, "application/pdf");

return File(new MemoryStream(ep.GetAsByteArray()), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"Relatorio.xlsx");

When the request can be made by get, I do it as follows:

window.open(urlComParametros, "_blank");

In this way a new tab is opened, if the file type is pdf it opens for viewing, and if the type is excel the file is downloaded.

But now I need to make the requisition per post. I already have, converting the file to byte [] and then converting to Base64String. So, in the success of my request I do the following to open the files:

window.open("data:application/pdf;base64," + data, "_blank");
window.open("data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," + data, "_blank");

That way it works, but there are some issues:

  • I could not change the tab title
  • I could not change the name of the excel file that is downloaded
  • Does not work in IE

How can I solve these problems? Or is there any better way to return these files?

    
asked by anonymous 02.02.2017 / 17:04

1 answer

1

For the tab title case, you can use JavaScript. An example using jQuery:

var wnd = window.open("data:application/pdf;base64," + data, "_blank");
$(wnd.document).find('html').append('<head><title>Um título</title></head>');

For Excel, the file name must be set to Controller . For your case, use this form of File() , but since you defined a window.open , the difficulty increases a little more.

So, we can use the idea of an invisible link, which is still a "technical device", instead of window.open :

var uri = 'data:application/pdf;base64," + data;

var downloadLink = document.createElement("a");
downloadLink.href = uri;
downloadLink.download = "meuarquivo.pdf";

document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);

In the case of IE, you can use this other ~ technical device ~ (note that it is CSV, not XSL or XSLX):

var IEwindow = window.open();
IEwindow.document.write('sep=,\r\n' + CSV);
IEwindow.document.close();
IEwindow.document.execCommand('SaveAs', true, nomeArquivo + ".csv");
IEwindow.close();
    
02.02.2017 / 19:03