可以异步下载文件吗?或者我做错了什么?

时间:2015-06-11 17:11:40

标签: c# asp.net ajax asp.net-mvc

我试图找出为什么我的文件下载操作不再有效。视图是

using(Ajax.BeginForm("DownloadFile",
"FileBundle",
new AjaxOptions { HttpMethod = "POST", OnSuccess = "dwnldFileCallback" }))
{
    <input name="fileName" type="hidden" id="file2Download" />
}

向下呈现

<form action="/myProject/myController/DownloadFile" data-ajax="true" data-ajax-method="POST" data-ajax-success="dwnldFileCallback" id="form1" method="post">        
     <input name="fileName" type="hidden" id="file2Download" />
</form>  

和myController中的DownloadFile函数是

[HttpPost]
public ActionResult DownloadFile ( string fileName )
{
    if (Session["isAuthenticated"] == "true")
    {
        string fullFilePath = Server.MapPath("~/Assets") + "/" + fileName;
        byte[] fileBytes = GetFile(fullFilePath);
        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
    }
    else
    {
        return Content("Not authenticated");
    }
}

并没有被召唤。当我的视图

时,它被召回
using (Html.BeginForm("DownloadFile",
    "FileBundle",
    FormMethod.Post,
    new { enctype = "multipart/form-data" }))
    {
        <input name="fileName" type="hidden" id="file2Download" />
    }

所以我所做的就是把它改成异步程序。那是我能做的吗?或者还有其他错误吗?或者我是否需要发布更多代码供您查看?

1 个答案:

答案 0 :(得分:0)

确保正确启用了不显眼的ajax:

jquery lib必须包含在页面中:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

还必须在web.config中的appSettings下设置以下键:

<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>

[编辑] 但是当我想到它时:你想向用户发布下载吗?如果这就是您想要的,那么这将无法正常工作,因为通信将在AJAX上下文中发生,因此不会提示用户输入该文件。

相关问题