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

Asked

Viewed 1,742 times

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

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.

However, now I need to do the request by post. I already did, 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 problems:

  • I couldn’t 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 resolve these issues? Or is there any better way to return these files?

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

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

As such, we can use the idea of an invisible link, which is still a technical device~, instead of the 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 artifice~ (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();
  • Dude, the append didn’t work because the pdf opens on that default pdf preview screen of Chrome and apparently it replaces the title for "date:". In the case of excel, where should I set the file name? Because I convert a Filestream into byte[] and then into a Base64 string, but none of these places can change the name. Thanks for your help!

  • @Andrémoraismartins I updated the answer.

  • Show! Thanks man!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.