简体   繁体   中英

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

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);

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM