Question

I have this function that I'm using to compress a list of files from the user's session, and then streaming it to the user's browser for download:

public static void DownloadAllPhotos()
{
    HttpContext.Current.Response.AddHeader(
        "Content-Disposition", "attachment; filename=Photos.zip");
    HttpContext.Current.Response.ContentType = "application/zip";

    List<string> photos= new List<string>();

    if (HttpContext.Current.Session != null && 
        HttpContext.Current.Session["userPhotos"] != null)
    {
        photos = (List<string>)HttpContext.Current.Session["userPhotos"];
    }

    using (var zipStream = new 
        ZipOutputStream(HttpContext.Current.Response.OutputStream))
    {
        foreach (string photoUrl in photos)
        {
            byte[] fileBytes = File.ReadAllBytes(photoUrl);

            var fileEntry = new ZipEntry(
                Path.GetFileName(photoUrl))
            {
                Size = fileBytes.Length
            };

            zipStream.PutNextEntry(fileEntry);
            zipStream.Write(fileBytes, 0, fileBytes.Length);
        }

        zipStream.Flush();
        zipStream.Close();

        // reset session
        HttpContext.Current.Session["userPhotos"] = new List<string>();
    }
}

When the user has photo urls in their session, and they click a button to call this function, the files are compressed and the download starts in the user's browser.

But when I try to open the compressed file, I get this error:

Windows cannot open the folder.

The compressed folder "{Path to my file}" is invalid.

Am I doing something wrong that's causing this error?

Était-ce utile?

La solution

Check out the placement of Response.Flush and ZipEntry.CleanName in this example and see if writing something similar corrects the problem.

Autres conseils

Also per the example in @cfeduke 's answer, there is a comment in the 'Create a Zip as a browser download attachment in IIS' that suggests changing Response.ContentType = "application/octet-stream" instead of "application/zip"

// If the browser is receiving a mangled zipfile, IIS Compression may cause this problem. Some members have found that //Response.ContentType = "application/octet-stream" has solved this. May be specific to Internet Explorer.

Worked for me. And it was not IE specific (I use Chrome).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top