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

I think there is no need of Ajax call you can do simply using hyperlink as below example.

View Code

<a href="https://stackoverflow.com/questions/30704078/@Url.Action("DownloadAttachment", "PostDetail", new { studentId = 123 })">Download Form</a>

Controller Method

public ActionResult DownloadAttachment(int studentId)
{          
    // Find user by passed id
    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);                           
}

Leave a Comment