I need to initiate file download from ASP.NET page from javascript code.
What would be my best option? Is it possible to call a webservice to do so, or somehow call usual event handler of C# page?
Note that I will retrieve a large amount of data, many megabytes.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can use a hidden IFRAME element and initiate a file download request, which does give the feeling for a AJAX file download.
While the file is being downloaded you can do other activity in your form on client side.
Yes you can call a webservice or aspx page or http handler as well in this URL
function dowloadFileJS() {
// Create an IFRAME.
var iframe = document.createElement("iframe");
// Point the IFRAME to GenerateFile
iframe.src = "GenerateFile.aspx?yourQueryString=myQueryString";
// This makes the IFRAME invisible to the user.
iframe.style.display = "none";
// Add the IFRAME to the page. This will trigger a request to GenerateFile now.
document.body.appendChild(iframe);
}
Method 2
You can use Javascript to create an iframe to the file you want to download. Have a look at this answer: Starting file download with JavaScript
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0