在MVC中使用Ajax不下载Zip文件

时间:2015-09-11 11:02:33

标签: javascript c# jquery ajax model-view-controller

我想通过ajax调用下载包含.pdf文件的zip文件。这是我的代码。只有zip文件没有下载,其余的都没问题。

public FileResult DownloadZip(string[] Paths) {
    string FilePath = string.Empty;
    using (ZipFile zip = new ZipFile()) {
        foreach (var item in Paths) {
            string updateitem = item.Replace("'", "");
            FilePath = System.Configuration.ConfigurationManager.AppSettings["ReportPath"] + updateitem;

            if (System.IO.File.Exists(FilePath)) {
                if (!System.IO.File.Exists(FilePath)) { continue; }
                if (!zip.ContainsEntry(FilePath)) { zip.AddFile(FilePath); }
            }
        }

        Response.Clear();
        Response.AddHeader("Content-Disposition",attachmentfilename=DocumentFiles.zip");
        Response.ContentType = "application/zip";

        var memStream = new MemoryStream();
        zip.Save(Response.OutputStream);
        memStream.Position = 0;

        return File(memStream, "application/zip", "DocumentFiles.zip");
    }
}

$("#btnDownload").click(function () {
    var reportPaths = new Array();
    $('input[name="path"]:checked').each(function() {
        reportPaths.push(this.value);
    });
    $.ajax({type: "GET",url: "/Client/CompletedCases/DownloadZip",traditional: true,data:{Paths:reportPaths},success: function (data) {},});
});

1 个答案:

答案 0 :(得分:0)

[HttpGet]
public virtual ActionResult Download(string file)
{   
  string fullPath = Path.Combine(Server.MapPath("~/MyFiles"), file);
  return File(fullPath, "application/zip", file);
}

$.ajax({
    type: 'POST',
    url: '/Download', //change it accroding to your url
    data: '{ "file" : "file" }',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (returnValue) {
        window.location = '/Download?file=' + returnValue; //change accroding to you url
    }
});