Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File download in Asp.Net MVC 2

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?

like image 237
Anders Avatar asked Aug 30 '10 00:08

Anders


1 Answers

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.

like image 139
Ian Mercer Avatar answered Sep 28 '22 12:09

Ian Mercer