Search code examples
c#javascriptasp.nethttpresponseashx

Closing the tab in browser after calling a ashx handler


Besides it is similar question I cannot find solution to my problem. I am also not very skilled with JavaScript.

I create a ashx handler for downloading files from sharepoint site. All works fine when file in database exist. If file does not exist I should pop-up alert.

In ashx I create:

 var r = context.Response;
        var attachmentID = context.Request.QueryString[QueryKeyID];
        int id = 0;
        if (!String.IsNullOrEmpty(attachmentID))
        {
            id = Convert.ToInt32(attachmentID);

            DocKey k = new DocKey() { id = id };


            DocImage od = MyWebService.GetDocImage(k);
            String newFile = "document.doc";

            r.ContentType = GetMimeTypeByFileName(newFile);
            r.AppendHeader("Content-Type", GetMimeTypeByFileName(newFile));
            r.AppendHeader("content-disposition", "attachment; filename=" + newFile);
            r.BufferOutput = false; //Stream the content to the client, no need to cache entire streams in memory...
            r.BinaryWrite(od.image);
            r.End();
        }
        else
        {
            r.Write("<script type='text/javascript'>alert('no doc');</script>");
            r.End();

        }

If file exist it open open/save dialog and tab is closed after clicking any option. But if file does not exist alert is shown and the blank tab does not disappear.

Download starts after clicking this link which is in gridView :

<asp:TemplateField HeaderText="">
                <ItemTemplate>
                    <asp:HiddenField ID="hdnkey" runat="server" Value='<%# getKey(Eval("Key")) %>' />
                    <a href="/_LAYOUTS/UserHandler/AttachmentHandler.ashx?ID='<%# getKey(Eval("Key")) %>'" target="_blank">download</a>      
                </ItemTemplate>
            </asp:TemplateField>

I want to make auto cloasing the blank tab after alert.


Solution

  • Try this:

    r.Write("<script type='text/javascript'>alert('brak dokumentu w bazie');window.close();</script>");
    

    It should work unless it's blocked by some security setting on the browser.