File download in Asp.Net MVC 2

≡放荡痞女 提交于 2019-11-27 06:20:59

问题


I want to enable file download in my MVC application, without simply using a hyperlink. I plan to use an image or the like and make it clickable by using jQuery. At the moment I have a simple just for testing.

I found an explanation of doing the download through an action method, but unfortunately the example still had actionlinks.

Now, I can call the download action method just fine, but nothing happens. I guess I have to do something with the return value, but I don't know what or how.

Here's the action method:

    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)
        };
    }

Here's the BinaryContentResult class:

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();
    }
}

I call the action method via:

<span id="downloadLink">Download</span>

which is made clickable via:

$("#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?
    });
});

Note that the fileName parameter is received correctly by the action method and everything, it's just that nothing happens so I guess I need to handle the return value somehow?


回答1:


You don't want to download the file using AJAX, you want the browser to download it. $.get() will fetch it but there's no way to save locally from Javascript, for security reasons the browser needs to be involved. Simply redirect to the download location and the browser will handle it for you.



来源:https://stackoverflow.com/questions/3597179/file-download-in-asp-net-mvc-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!