Search code examples
c#asp.net-mvcasp.net-mvc-3jqueryfileresult

FileResult is not prompt in mvc3


I create MVC 3 application in vs 2010. I try to a download a file in the filder.

this is my Action in MVC. Please see my code.

    //[HttpPost]
    public FileResult Download(string url, string cnt)
    {
        if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(cnt))
        {
            return File(url, cnt);
        }
        else
        {
            return null;
        }

    }



 <input type="button" id="@(Model.ControlID)_bio_view" class="changepasswordbutton" value="View" />

And i create a jQuery function in my .cshtml file

 function ViewFile(url, cnt) {
    $.post('@(Url.Action("Download"))?url=' + url + '&cnt=' + cnt)
}
 $('#@(Model.ControlID)_bio_view').click(function (e) {

    ViewFile($('#bio_file_url').val(), $('#bio_file_url').attr("cnttype"));

});

This function is fired correctly when i click the Download button. But no file download window is prompted.

Please help.


Solution

  • No, you cannot download files using an AJAX request. You need to redirect the browser to the target url instead of sending an AJAX request:

    function ViewFile(url, cnt) {
        window.location.href = '@(Url.Action("Download"))?' + 
            'url=' +  encodeURIComponent(url) + 
            '&cnt=' + encodeURIComponent(cnt);
    }
    

    Also bear in mind that the File function expects as first argument an absolute physical path to the file such as:

    public ActionResult Download(string url, string cnt)
    {
        if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(cnt) && File.Exists(url))
        {
            return File(url, cnt);
        }
        return HttpNotFound();
    }
    

    Also if you want to prompt for the file to download you need to specify a filename (3rd argument of the File function):

    return File(@"c:\reports\foo.pdf", "application/pdf", "foo.pdf");