我想在我的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)
};
}
这是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();
}
}
我通过以下方式调用action方法:
通过以下方式点击:
$("#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?
});
});
请注意,actionName参数是由action方法正确接收的所有内容,只是没有任何反应,所以我想我需要以某种方式处理返回值?
最佳答案
您不想使用AJAX下载文件,您希望浏览器下载它. $.get()将获取它,但由于安全原因浏览器需要参与,因此无法从Javascript本地保存.只需重定向到下载位置,浏览器就会为您处理.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。