【问题标题】:Zip file not downloading using Ajax in MVC未在 MVC 中使用 Ajax 下载 Zip 文件
【发布时间】:2015-09-11 11:02:32
【问题描述】:

我想通过 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) {},});
});

【问题讨论】:

  • Here is my code.
  • 什么代码......我喜欢这个代码......我可以借用一下:D:D
  • 我正在编辑代码。
  • 在 ajax 成功时你什么也没做......你必须根据你的 ajax 请求的响应编写代码
  • 但我正在用 c# 代码返回一个文件。

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


【解决方案1】:
[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
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多