我已阅读过使用Ajax和iframe进行文件下载的内容。 任何人都可以给我一步一步解释如何做到这一点或知道任何教程,因为我们已经在这个项目上使用ajax这似乎是最好的方法。
编辑:
好的,这是我的观看代码:
<div class="buttons">
<input type="button" value="Download File" class="button" id="downloadfile">
<script type="text/javascript">
$(function () {
$('#downloadfile').click(function (e) {
$('#downloadIframe').attr('src', '@Url.Action("DownloadFile","Invoice")' + '/Report/Invoices');
});
});
</script>
这是我的控制者:
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
中的一行,然后打开视图Download
,然后在视图中点击按钮,它应该在视图中执行script
并在控制器中返回DownloadFile
FileResult
,但单击按钮时没有任何反应。
报告所在的文件夹:~/Reports/Invoices
答案 0 :(得分:2)
我不知道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();
}
答案 1 :(得分:0)
这是解决方案 -
假设您有这样的控制器 -
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操作将返回以下视图 -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$('#downloadfile').click(function (e) {
$('#downloadIframe').attr('src', '@Url.Action("Download","Submit")' + '/Report');
});
});
</script>
<input type="button" value="Download file" id="downloadfile"/>
<iframe id="downloadIframe"></iframe>
点击按钮 - “下载文件”后,您将获得iframe,其中包含我们指定下载Report.pdf的URL(根据您的需要,这可以是动态的)。
答案 2 :(得分:0)
您无法使用ajax触发下载。但您可以通过将网址设置为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") ";