And*_*ers 5 jquery download asp.net-mvc-2
我想在我的MVC应用程序中启用文件下载,而不是简单地使用超链接.我计划使用图像等,并使用jQuery使其可点击.目前我有一个简单的测试.
我找到了通过动作方法进行下载的解释,但遗憾的是该示例仍然有动作链接.
现在,我可以调用下载操作方法,但没有任何反应.我想我必须对返回值做一些事情,但我不知道是什么或如何.
这是动作方法:
public ActionResult Download(string fileName)
{
string fullName = Path.Combine(GetBaseDir(), fileName);
if (!System.IO.File.Exists(fullName))
{
throw new ArgumentException("Invalid file name or file does not exist!");
}
return new BinaryContentResult
{
FileName = fileName,
ContentType = "application/octet-stream",
Content = System.IO.File.ReadAllBytes(fullName)
};
}
Run Code Online (Sandbox Code Playgroud)
这是BinaryContentResult类:
public class BinaryContentResult : ActionResult
{
public BinaryContentResult()
{ }
public string ContentType { get; set; }
public string FileName { get; set; }
public byte[] Content { get; set; }
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.ClearContent();
context.HttpContext.Response.ContentType = ContentType;
context.HttpContext.Response.AddHeader("content-disposition",
"attachment; filename=" + FileName);
context.HttpContext.Response.BinaryWrite(Content);
context.HttpContext.Response.End();
}
}
Run Code Online (Sandbox Code Playgroud)
我通过以下方式调用action方法:
<span id="downloadLink">Download</span>
Run Code Online (Sandbox Code Playgroud)
通过以下方式点击:
$("#downloadLink").click(function () {
file = $(".jstree-clicked").attr("rel") + "\\" + $('.selectedRow .file').html();
alert(file);
$.get('/Customers/Download/', { fileName: file }, function (data) {
//Do I need to do something here? Or where?
});
});
Run Code Online (Sandbox Code Playgroud)
请注意,actionName参数是由action方法正确接收的所有内容,只是没有任何反应,所以我想我需要以某种方式处理返回值?
您不想使用AJAX下载文件,而是希望浏览器下载它。$ .get()将获取它,但是由于安全原因,需要使用浏览器,因此无法从Javascript本地保存。只需重定向到下载位置,浏览器就会为您处理。