How to show a message and send a file using ASP.NE

2020-04-15 15:53发布

问题:

I generate a set of letters in a file, but if there are errors then the file may be incomplete. I want to send the file anyway, but with a warning to the user. So I have this:

      string errMessage;
        string filePath = CCGTMarblox.Admin.Helpers.DocumentHelper.GenerateRejectionLetters(grantIDs, out errMessage);

        if (!String.IsNullOrEmpty(errMessage))
        {
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "problem", String.Format("alert('{0}');", errMessage), true);
        }

        if (filePath != null)
        {
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
            Response.ClearHeaders();
            Response.AddHeader("Content-Disposition", string.Format(@"attachment; filename=""{0}""", fileInfo.Name));
            Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            Response.ContentType = "application/octet-stream";
            Response.TransmitFile(fileInfo.FullName);
            Response.Flush();
        }

The problem is that the the alert is not shown when the code to download the file is included - the headers are cleared and it's like a new Response. Is there any way I can send the script and the file? I tried to Response.Redirect to a page that retrieves the file, but that didn't work either.

Actually, what I did in the end was send another start-up script that does a similar task to the redirect that I tried in the question. (I already have a page that handles downloads).

Edit (added after answer was accepted)

string script = String.Format("window.location = '{0}';", url);        
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "goToDownload", script, true);

回答1:

I would suggest to have a page which would instruct the users the file download will begin shortly and in this page, you can display any warnings.

This page would make a separate request for the file, using JS / meta refresh and continue the download. You may also want to provide a direct link, if the download doesn't begin in specified time.



回答2:

You can't return HTML and another response (for file's stream) in single GET.

You can return HTML and have link to download file there.



标签: c# asp.net