【发布时间】:2011-04-05 13:27:01
【问题描述】:
我想在我的 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();
}
}
我通过以下方式调用操作方法:
<span id="downloadLink">Download</span>
可通过以下方式点击:
$("#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?
});
});
请注意,操作方法和所有内容都正确接收了fileName参数,只是什么也没发生,所以我想我需要以某种方式处理返回值?
【问题讨论】:
-
您的
BinaryContentResult类不应该存在。使用FileResult。 -
好的,这是标准课程还是什么?它将如何帮助我解决问题?
标签: jquery asp.net-mvc-2 download