在ASP.NET MVC中将文件作为zip文件下载损坏的zip文件下载

时间:2017-09-21 19:03:14

标签: c# asp.net asp.net-mvc zip

我有一个托管大型XML文件存档的服务器,并且API在zip中检索所请求的文件。如果我选择大约11个或更少的文件,zip返回就好了。如果我检索更多,我在尝试打开zip时收到以下错误:

  

“Windows无法打开文件夹。压缩(zipped)文件夹是   无效“。

以下是创建zip的数据类和方法:

//Archive file containing filename and content as memory stream
public class ArchiveFile {
    public string FileName;
    public System.IO.MemoryStream FileContent;
}

//Method to retrieve archive files and zip them
public static System.IO.MemoryStream GetFilesAsZip (string[] arrFileNames) {
    MemoryStream zipStream  = null;
    using (zipStream = new MemoryStream()) {
        // Retrieve files using above method
        ArchiveFile[] retrievedFiles = GetFilesFromArchive(arrFileNames);
        // Initialize new ZipArchive on the return object's MemoryStream property
        using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Update, leaveOpen: true)) {
            // Write file entries into archive
            foreach (ArchiveFile dataFile in retrievedFiles) {
                if (dataFile.FileContent != null) {
                    // Create new ZipArchiveEntry with content
                    ZipArchiveEntry zipEntry = archive.CreateEntry(dataFile.FileName);
                    dataFile.FileContent.WriteTo(zipEntry.Open());
                }//end if
            } // end foreach
        } //end using
    } //end using
    return zipStream;
}//end method

//API to return content to user as an MVC File Content Result
[HttpGet]
public ActionResult DownloadFiles (string [] fileNames) {
    FileContentResult data = new FileContentResult(GetFiles(fileNames).GetBuffer(), “application/zip”) { FileDownloadName = “files.zip” };
    return data;
} //end method

在写入内存流时,损坏可能与空间分配有关。我注意到我所有的“成功”拉链(11个或更少的文件)大小为259 KB,但所有“不成功”的拉链(超过11个文件)大小为517 KB,一些较大的尝试拉链大小为1034 KB。这让我感到非常巧合,因为它们都是258.5 KB的倍数,特别是因为11个文件的拉链产生了259 KB的拉链,但是12个文件的拉链产生了517 KB的拉链。

有关它可能是什么的任何见解?

2 个答案:

答案 0 :(得分:1)

ASP.Net Core API Controller returns corrupted excel file

在你的控制器中返回

return new FileResult("demo.zip", Path.Combine(sWebRootFolder, sFileName), "application/zip");

添加此代码

public class FileResult : ActionResult
    {
        public FileResult(string fileDownloadName, string filePath, string contentType)
        {
            FileDownloadName = fileDownloadName;
            FilePath = filePath;
            ContentType = contentType;
        }

        public string ContentType { get; private set; }
        public string FileDownloadName { get; private set; }
        public string FilePath { get; private set; }

        public async override Task ExecuteResultAsync(ActionContext context)
        {
            var response = context.HttpContext.Response;
            response.ContentType = ContentType;
            context.HttpContext.Response.Headers.Add("Content-Disposition", new[] { "attachment; filename=" + FileDownloadName });
            using (var fileStream = new FileStream(FilePath, FileMode.Open))
            {
                await fileStream.CopyToAsync(context.HttpContext.Response.Body);
            }
        }
    }

您的代码已重构

public byte[] GetFilesAsZip (string[] arrFileNames) {
    byte[] buffer = null;
    using (MemoryStream zipStream = new MemoryStream()) {
        // Retrieve files using above method
        ArchiveFile[] retrievedFiles = GetFilesFromArchive(arrFileNames);
        // Initialize new ZipArchive on the return object's MemoryStream property
        using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Update, leaveOpen: true)) {
            // Write file entries into archive
            foreach (ArchiveFile dataFile in retrievedFiles) {
                if (dataFile.FileContent != null) {
                    // Create new ZipArchiveEntry with content
                    ZipArchiveEntry zipEntry = archive.CreateEntry(dataFile.FileName);
                    dataFile.FileContent.WriteTo(zipEntry.Open());
                }//end if
            } // end foreach
        } //end using
        buffer = zipStream.ToArray();
    } //end using
    return buffer;
}//end method

您应该可以将其更改为

FileContentResult data = new FileContentResult(GetFiles(fileNames), “application/zip”) { FileDownloadName = “files.zip” };

答案 1 :(得分:0)

我过去成功return File(fileLocation, "application/zip", fileName);,其中fileLocation是文件夹的路径,fileName是实际文件夹的名称。您可以在ActionResult

中执行此操作