views:

18

answers:

2

I'm working on a functionality in my asp.net web site that enables the user to download some files as a zip file. I'm using the DotNetZip library to generate the zip file.

My code looks like this:

protected void OkbtnZipExport_OnClickEvent(object sender, EventArgs e)
{
        var selectedDocumentIds = GetSelectedDocIds();

        string archiveName = String.Format("archive-{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));            
        AddResponseDataForZipFile(Response, archiveName);            

        try
        {
            string errorMessage = Utils.ExportToZip(selectedDocumentIds, arkivdelSearchControl.GetbraArkivConnection(), Response.OutputStream);
            if (!string.IsNullOrEmpty(errorMessage))
            {
               LiteralExportStatus.Text = errorMessage;                                                     
            }
            else
                LiteralExportStatus.Text = "Success";

        }
        catch (Exception ex)
        {
            LiteralExportStatus.Text = "Failure " + ex.Message;                
        }

        Response.Flush();
        Response.Close();
        HttpContext.Current.ApplicationInstance.CompleteRequest();
}

private void AddResponseDataForZipFile(HttpResponse response, string zipName)
{
        Response.Clear();
        Response.BufferOutput = false;
        Response.ContentType = "application/x-zip-compressed";
        Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
        Response.AddHeader("Expires", "0");
        Response.AddHeader("Content-Description", "Zip Arcive");
}

Now, if anything goes wrong, say the Utils.ExportToZip method fails, I want to present an error message to the user and not the download dialog. Do I have to remove some data from the Response object in order to cancel the download operation?

Best regards

OKB

+1  A: 

I can't comment at the moment, so take this answer as one.

How does Utils.ExportToZip work? If the reason it takes the Response.OutputStream for the constructor is to write the zip-file directly into it, then you need to set Buffering in order to "undo" that in your AddResponseDataForZipFile Method:

Response.BufferOutput = true;
Bora