jqueryjsonasp.net-mvc-4asp.net-ajax

How to download a file through ajax request in asp.net MVC 4


Below is my code :

ActionResult DownloadAttachment(student st)
{          
    var file = db.EmailAttachmentReceived.FirstOrDefault(x => x.LisaId == st.Lisaid);

    byte[] fileBytes = System.IO.File.ReadAllBytes(file.Filepath);
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, file.Filename);                 
}

This is the script which i'm using

$(function () {
    $("#DownloadAttachment").click(function () {
        $.ajax({
            url: '@Url.Action("DownloadAttachment", "PostDetail")',
            contentType: 'application/json; charset=utf-8',
            datatype: 'json',
            type: "GET",
            success: function () {
                alert("sucess");
            }
        });    
    });
});      

How to return the file for download pursing above code?


Solution

  • Please, try this in ajax success

    success: function () {
        window.location = '@Url.Action("DownloadAttachment", "PostDetail")';
    }
    

    Updated answer:

    public ActionResult DownloadAttachment(int studentId)
    {          
        // Find user by passed id
        // Student student = db.Students.FirstOrDefault(s => s.Id == studentId);
    
        var file = db.EmailAttachmentReceived.FirstOrDefault(x => x.LisaId == studentId);
    
        byte[] fileBytes = System.IO.File.ReadAllBytes(file.Filepath);
    
        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, file.Filename);                       
    
    }
    

    Ajax request:

    $(function () {
            $("#DownloadAttachment").click(function () {
                $.ajax(
                {
                    url: '@Url.Action("DownloadAttachment", "PostDetail")',
                    contentType: 'application/json; charset=utf-8',
                    datatype: 'json',
                    data: {
                        studentId: 123
                    },
                    type: "GET",
                    success: function () {
                        window.location = '@Url.Action("DownloadAttachment", "PostDetail", new { studentId = 123 })';
                    }
                });
    
            });
        });