在Asp.Net MVC 2中下载文件

时间:2010-08-30 00:33:03

标签: jquery asp.net-mvc-2 download

我想在我的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?
    });
});

请注意,actionName参数是由action方法正确接收的,只是没有任何反应,所以我想我需要以某种方式处理返回值?

1 个答案:

答案 0 :(得分:5)

您不想使用AJAX下载文件,您希望浏览器下载它。 $ .get()将获取它,但由于安全原因浏览器需要参与,因此无法从Javascript本地保存。只需重定向到下载位置,浏览器就会为您处理。