문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top