使用Ajax和iframe下载文件

我读过有关使用Ajax和iframe进行文件下载的文章。 任何人都可以给我一步一步解释如何执行此操作或知道任何教程,因为我们已经在此项目上使用ajax这似乎是最好的方法。

编辑:

好的,这是我的查看代码:

  $(function () { $('#downloadfile').click(function (e) { $('#downloadIframe').attr('src', '@Url.Action("DownloadFile","Invoice")' + '/Report/Invoices'); }); });  

这是我的控制器:

 public FileResult DownloadFile(int id) { byte[] fileBytes = System.IO.File.ReadAllBytes(Server.MapPath("~/Reports/Invoices/" + Table.First(x => x.ID == id).ID + ".pdf")); string fileName = Table.First(x => x.ID == id).ID.ToString(); return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Pdf, fileName); } public ActionResult Download(int id) { return AjaxResponse("Download", null); } 

我有一个Jquery上下文菜单,我用它来点击JQGrid中的JQGrid ,然后打开视图Download ,然后在视图中我单击按钮,它应该在视图中执行script并返回控制器中的DownloadFile FileResult但是没有当我点击按钮时发生。

报告所在的文件夹: ~/Reports/Invoices

我不知道iframe,但我通过ajax下载文件的方式只是简单地写入响应流。

  [HttpGet] [OutputCache(VaryByCustom="id")] public void DownloadFile(int id) { var path = GetFilePath(id); Response.ContentType = "application/octet-stream"; Response.AppendHeader("Content-Disposition", "attachment; filename=xxx"); Response.WriteFile(path); Response.End(); } 

这是解决方案 –

假设你有这种方式的控制器 –

 public class SubmitController : Controller { public ActionResult Index() { return View(); } public ActionResult Download(string id) { string filename = String.Format("{0}.pdf", id); return File(System.IO.File.ReadAllBytes(Server.MapPath("~/Content/") + filename), "application/octet-stream", filename); } } 

Index行动将返回以下视图 –

     

单击按钮 – “下载文件”后,您将获得iframe,其中包含我们指定下载Report.pdf的URL(根据您的需要,这可以是动态的)。

你不能使用ajax触发下载。 但您可以通过将URL设置为window.location来进行文件下载

在你c#中返回文件

 byte[] bytes = .... insert your bytes in the array return File(bytes, System.Net.Mime.MediaTypeNames.Application.Octet, "somefilename.exe"); 

在js

 window.location="download.action?para1=value1...." 

否则,您可以使用处理下载的jquery.FileDownload插件。

编辑

尝试

 window.location=" @string.Format("{0}{1}{2}","~/Reports/Invoices/",ViewBag.ID,".pdf") ";