我有
public class FileController : AsyncController
{
public ActionResult Download(FormCollection form)
{
FileContentResult file = new FileContentResult(Encoding.UTF8.GetBytes("10k file size"),"application/vnd.xls");
file.FileDownloadName = "test.xls";
return file;
}
}
当然,ajax形式
<% var form = Ajax.BeginForm(...) %>
<input type="image" src="...gif" /> // this is my 1st attempt
<%= Ajax.ActionLink(...) %> // 2nd attempt
<% form.EndForm(); %>
问:如何使用Async Controller进行精美的文件下载
问:如何使Ajax.ActionLink看起来不错
您无法使用Ajax从服务器下载文件。这样做的原因是,即使您成功在success
回调中向服务器发出异步请求,您也将获得从服务器发送的文件内容,并且您无法在客户端对此文件做很多事情。请记住,javascript无法访问文件系统,因此您无法保存它。实现这一目标的方法是拥有一个普通的HTML <form>
,它将指向Download
动作。提交此表单后,将要求用户选择要保存文件的位置,然后继续下载。此外,您不需要AsyncController。
这是一个例子:
public class FileController : Controller
{
[HttpPost]
public ActionResult Download()
{
return File(
Encoding.UTF8.GetBytes("10k file size"),
"application/vnd.xls",
"test.xls"
);
}
}
在你的视图中:
<% using (Html.BeginForm("download", "file", FormMethod.Post)) { %>
<input
type="image"
src="<%: Url.Content("~/content/images/download.png") %>"
value="download"
alt="download"
/>
<% } %>
为了使下载按钮看起来不错,你可以创建一个很好的download.png
图像,它将用作表单提交按钮。
我用这个:
禁用
$('form').removeAttr("data-ajax");
启用
$('form').attr("data-ajax", "true");
对于一个表单,其中3提交1以刷新2以下载文件所有帖子都发布到同一个ActionResult但其中2个有下载为csv或pdf的参数
下载时只禁用ajax提交。
我找到了一个方法!!
只需创建具有常规表单的iframe并使用jquery来触发。
$("iframe").contents().find("form").submit();
:d
ps信用Firebug + Google Doc。