如何在ZIP中下载多个文件

时间:2018-07-17 12:47:15

标签: jquery asp.net-web-api ziparchive

我正在尝试从项目文件夹中读取几张pdf文件,并使其压缩并尝试下载。我正在使用ZipArchieve创建zip文件。

public HttpResponseMessage Get()
    {
        var path = System.Web.Hosting.HostingEnvironment.MapPath("~/zipfiles/test.zip");
        if (System.IO.File.Exists(path))
        {
            System.IO.File.Delete(path);
        }
        ZipArchive zip = ZipFile.Open(path, ZipArchiveMode.Create);

        var selectedfiles = Directory.GetFiles(System.Web.Hosting.HostingEnvironment.MapPath(@"/pdf"));
        int i = 0;
        foreach (string file in selectedfiles)
        {
            FileStream fileStream = System.IO.File.Open(file, FileMode.Open);
            byte[] fileBytes = new byte[fileStream.Length];
            fileStream.Read(fileBytes, 0, Convert.ToInt32(fileStream.Length));

            var demoFile = zip.CreateEntry("test" + i + ".pdf");

            using (var entryStream = demoFile.Open())
            {
                using (var fileToCompressStream = new MemoryStream(fileBytes))
                {
                    fileToCompressStream.CopyTo(entryStream);
                    fileToCompressStream.Close();
                }
                entryStream.Close();
            }
            i++;
            fileStream.Close();
        }

        zip.Dispose();

        MemoryStream ms = new MemoryStream();
        using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            file.CopyTo(ms);

        }

        ms.Position = 0;
        var response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StreamContent(ms); 
        response.Content.Headers.ContentType =
        new MediaTypeHeaderValue("application/octet-stream");
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "file.zip"
        };

        return response;

    }

JS代码:

<p id="downloadfile">Download File</p>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
    $('#downloadfile').on('click', function () {
        $.ajax({
            url: "/api/download",
            success: function (result) {
                var file = new Blob([result], { type: "application/octet-stream" });
                var a = document.createElement('a');
                var url = window.URL.createObjectURL(file);
                a.href = url;
                a.download = 'myfile.zip';
                a.click();
                window.URL.revokeObjectURL(url);
            }
        });
    })
</script>

单击“下载”后,现在文件已下载,但是当我尝试打开zip文件时,出现文件已损坏的错误消息。

能否请别人建议我错了。

0 个答案:

没有答案