Reputation: 139
I have an ASPX form page that works synchronously (no AJAX!).
One of the buttons on this page returns a file to be downloaded by writing it directly into response stream:
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=logfile.txt");
Response.TransmitFile(Server.MapPath("~/wmtest.docx"));
Response.End();
I need a javascript callback to be called on the page when response is returned, just before or after browser displays the "download file" dialog.
Is there any way to do that?
Note: It's not real phisical file existing on the server that can be accessed or downloaded by URL, but a file that is generated and returned within request, so returning file's URL and then making it to be downloaded with JS on the client side is not an option
Thanks in advance! - Michael
Upvotes: 1
Views: 1338
Reputation: 4207
Since your response is returning a stream as a content type you can't return html/javascript with the same response. I suggest creating a dedicated download.aspx or similar to download the file and open that with javascript:
download.aspx (empty - no html):
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="download.aspx.cs" Inherits="WebApplication2.download" %>
download.aspx.cs (Page_Load):
public partial class download : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=logfile.txt");
Response.TransmitFile(Server.MapPath("~/wmtest.docx"));
Response.End();
}
}
And downloading the file from your page:
<input type="button" class="js-download" value="Download file"/>
<script>
var button = document.getElementsByClassName("js-download")[0];
button.addEventListener("click", function () {
window.open("download.aspx", "download");
console.log("download starting....")
});
</script>
Upvotes: 1