1

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

2
  • Did you try using ClientScriptManager.RegisterStartupScript(Type, String, String, Boolean) method to call your javascript code? Commented Nov 17, 2016 at 8:31
  • Hmmm...No, but I'm sure it won't work. Response returns content of the binary file-to-be-downloaded. It doesn't affect the original HTML and cannot return script... Commented Nov 17, 2016 at 13:56

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.