【问题标题】:How to download a file through ajax request in asp.net MVC 4如何在asp.net MVC 4中通过ajax请求下载文件
【发布时间】:2015-08-22 14:53:26
【问题描述】:

下面是我的代码:

ActionResult DownloadAttachment(student st)
{          
    var file = db.EmailAttachmentReceived.FirstOrDefault(x => x.LisaId == st.Lisaid);

    byte[] fileBytes = System.IO.File.ReadAllBytes(file.Filepath);
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, file.Filename);                 
}

这是我正在使用的脚本

$(function () {
    $("#DownloadAttachment").click(function () {
        $.ajax({
            url: '@Url.Action("DownloadAttachment", "PostDetail")',
            contentType: 'application/json; charset=utf-8',
            datatype: 'json',
            type: "GET",
            success: function () {
                alert("sucess");
            }
        });    
    });
});      

上面的代码如何返回下载文件?

【问题讨论】:

    标签: jquery json asp.net-mvc-4 asp.net-ajax


    【解决方案1】:

    我认为不需要 Ajax 调用,您只需使用以下示例的超链接即可。

    查看代码

    <a href="@Url.Action("DownloadAttachment", "PostDetail", new { studentId = 123 })">Download Form</a>
    

    控制器方法

    public ActionResult DownloadAttachment(int studentId)
    {          
        // Find user by passed id
        var file = db.EmailAttachmentReceived.FirstOrDefault(x => x.LisaId == studentId);    
        byte[] fileBytes = System.IO.File.ReadAllBytes(file.Filepath);    
        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, file.Filename);                           
    }
    

    【讨论】:

    • 这个例子对我有用。此示例发送一个 HttpGet 请求,因此请求中的数据负载(只有一个记录 ID)作为参数包含在 URL 中。但是,如果我想发送一个 HttpPost 请求,并将数据负载作为对象(包含许多字段)包含在请求中怎么办?
    • 另外,我可以在 HttpPost 请求中包含 AntiForgeryToken 吗?
    【解决方案2】:

    请在 ajax 中试试这个成功

    success: function () {
        window.location = '@Url.Action("DownloadAttachment", "PostDetail")';
    }
    

    更新答案:

    public ActionResult DownloadAttachment(int studentId)
    {          
        // Find user by passed id
        // Student student = db.Students.FirstOrDefault(s => s.Id == studentId);
    
        var file = db.EmailAttachmentReceived.FirstOrDefault(x => x.LisaId == studentId);
    
        byte[] fileBytes = System.IO.File.ReadAllBytes(file.Filepath);
    
        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, file.Filename);                       
    
    }
    

    Ajax 请求:

    $(function () {
            $("#DownloadAttachment").click(function () {
                $.ajax(
                {
                    url: '@Url.Action("DownloadAttachment", "PostDetail")',
                    contentType: 'application/json; charset=utf-8',
                    datatype: 'json',
                    data: {
                        studentId: 123
                    },
                    type: "GET",
                    success: function () {
                        window.location = '@Url.Action("DownloadAttachment", "PostDetail", new { studentId = 123 })';
                    }
                });
    
            });
        });
    

    【讨论】:

    • 您是否更容易将模型 id 传递给操作,然后通过 id 找到您的学生并使用学生模型数据做任何您想做的事情。我已经更新了答案。
    • 基本上,如果我们不进行 ajax 调用,我们仍然可以通过 window.location 下载文件,这只是因为我们需要 ajax 请求,所以我们在成功函数中使用了相同的函数,感谢您的帮助。!跨度>
    • DownloadAttachment 方法没有双重访问权限?
    • 这将调用 DownloadAttachment 方法 2 次。如何避免?
    • 完全没有必要为此使用ajax。直接调用 window.location 即可。这一切所做的就是两次发出相同的请求。我不知道为什么这被赞成了。
    【解决方案3】:

    以下代码将帮助您在服务器中创建 pdf/excel 文件,并允许通过 ajax 调用在浏览器中下载。

    控制器用于创建 pdf/excel 文件

    public async Task<JsonResult> CardStatusReportExport(ReportFilterInputModel cardStatusReportInputModel, string type, string sortOrder)
        {
            cardStatusReportInputModel.ReportType = Reprot_Type_Const.CardStatus;
            cardStatusReportInputModel.ReportFormat = type;
    
            var CardStatusReport = await _reportDocGeneration.DocGeneartion(cardStatusReportInputModel);
            string result = Path.GetTempPath();
            string fileName = "CardStatusReport" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
            if (type.Equals(Constants.FILE_TYPE_PDF))
            {
                fileName = fileName + Constants.FILE_EXTENSION_PDF;
                System.IO.File.WriteAllBytes(result + fileName, CardStatusReport);
            }
            else
            {
                fileName = fileName + Constants.FILE_EXTENSION_EXCEL;
                System.IO.File.WriteAllBytes(result + fileName, CardStatusReport);
            }
            return Json(new { fileName = fileName});
        }
    

    以下控制器代码将允许从单个 ajax 调用下载创建的文件

    [HttpGet]    
        public async Task<ActionResult> Download(string file)
        {
            var path = Path.Combine(Path.GetTempPath(),file);
            var memory = new MemoryStream();
            try
            {
                using (var stream = new FileStream(path, FileMode.Open))
                {
                    await stream.CopyToAsync(memory);
                }
            }
            catch (Exception e)
            {
                ModelState.AddModelError("FileNotFoundError", e.Message);
                return Content(e.Message);
            }
            memory.Position = 0;
            return File(memory, GetContentType(path), Path.GetFileName(path));
        }
    
        private string GetContentType(string path)
        {
            var types = MediaType.GetMimeTypes();
            var ext = Path.GetExtension(path).ToLowerInvariant();
            return types[ext];
        }
    

    使用下面的 ajax 调用创建 pdf/excel 文件并下载。

    $.ajax({
                    method: 'POST',
                    data: { type: val, cardStatusReportInputModel: payload, sortOrder : sortOrder},
                    url: '@Url.Action("CardStatusReportExport", "Reports")'
                }).done(function (data, statusText, xhdr) {
                    try {
                        if (data.fileName != "") {
                            window.location.href = "@Url.RouteUrl(new { Controller = "Reports", Action = "Download"})/?file=" + data.fileName;
                            ShowMessageAlert('@Html.Raw(Localizer["Report has been exported successfully"].Value.ToString())');
                        }
                        $("#divLoader").hide();
                    }
                    catch (e) {
                        $("#divLoader").hide();
                    }
                }).fail(function (xhdr, statusText, errorText) {
                    alert('error');
                    $("#divLoader").hide();
                });
    

    【讨论】:

      【解决方案4】:
      public FileResult DownloadGeneralDocs(string docName)
          {
              string fileName = docName+".pdf";           
              var path = _globalWebSettings.Value.DownloadGeneralDocsPath;
              string filePath = "";
              if (fileName!="")
              {
                  filePath = (_env.WebRootPath + string.Format("{0}{1}",path, fileName));
              }
              FileInfo file1 = new FileInfo(filePath);            
              byte[] fileBytes = System.IO.File.ReadAllBytes(file1.FullName);
              return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);            
          }
      
      view.cshtml:
      <script>
      $(document).ready(function () {
          $("#docTable tbody tr td button").click(function (e) {
              var docName = $(this).closest("tr").find(".document_td_data").text();
              $.ajax({
                  url: '@Url.Action("DownloadGeneralDocs", "Documents")',                    
                      dataType: "html",
                      cache:false,
                      data: { 'docName': docName },
                      success: function (data) {                     
                          window.location.href = "@Url.RouteUrl(new
                      { Controller = "Documents", Action = "DownloadGeneralDocs" })/?docName=" + docName ;
      
                      },
                      error: function (err, response) {
                          console.log(err, response);
                          alert(err, response.responseText);
                      }
                  })
      
          });
      });
      

      【讨论】:

      • 一大段未经解释就被扔在网上的代码对任何人都没有帮助。您应该解释您的方法以及为什么您的答案比其他答案更好或不同。
      【解决方案5】:

      下面的方法将有助于从 jQuery 对话框窗口中调用 Ajax 请求中的动作并执行该动作,并且可以在动作返回成功结果后立即关闭对话框窗口

      控制器

          [HttpGet]
          public ActionResult DownloadCampaign(string filePath, string mode)
          {
              string contentType = string.Empty;
              var sDocument = filePath;
              if (!System.IO.File.Exists(sDocument))
              {
                  return HttpNotFound();
              }
      
              if (mode == "action")
                  return Json(new {fileName = filePath}, JsonRequestBehavior.AllowGet);
      
              if (sDocument.Contains(".pdf"))
              {
                  contentType = "application/pdf";
              }
              else if (sDocument.Contains(".docx"))
              {
                  contentType = "application/docx";
              }
              else if (sDocument.Contains(".xls"))
              {
                  contentType = "application/xlsx";
              }
      
              return File(sDocument, contentType, sDocument);
          }
      

      JQuery - Ajax 请求

      $(document)
          .ready(function() {
              $("#btnDownload").click(function () {
                  var file = $("#FilePath").val();
                  $.ajax({
                      url: '@Url.Action("DownloadCampaign", "FileList")',
                      data: { filePath: file, mode:'action' },
                      method: 'GET',
                      dataType: 'json',
                      //contentType: 'application/json; charset=utf-8',
      
                      success: function(data) {
                          @*window.location = '@Url.RouteUrl("DownloadCampaign", "FileList", new { filePath = data1.fileName })';*@
                          window.location.href = "@Url.RouteUrl(new
                          { Controller = "FileList", Action = "DownloadCampaign" })/?filePath=" + data.fileName + "&mode=download";
                          $("#downloadFile_dialog").dialog("close");
                      },
                      error: function (req, status, errorObj) {
                          alert("Error");
                      }
                  });
      
              });
      });
      

      如果您需要更多相关信息,请与我联系。

      【讨论】:

        猜你喜欢
        • 2021-09-08
        • 2012-11-11
        • 1970-01-01
        • 2018-11-09
        • 2023-04-07
        • 1970-01-01
        • 2011-10-16
        • 1970-01-01
        • 2013-05-16
        相关资源
        最近更新 更多