Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 430
rohit singh Avatar asked Jun 08 '15 08:06

rohit singh


People also ask

Can we download file using ajax?

We cannot download the file through Ajax, must use XMLHttpRequest.

How can I download Excel file in ASP NET MVC?

Create ASP.NET MVC Project Thus, go to Visual C# < Web and then from the right pane, just choose ASP.NET Web Application. Provide the name of the Application “ExportExcelDemo” and click OK. It will give you another dialog Window, where you can choose the type of the ASP.NET project[Web Forms, MVC, Web APIs etc].


1 Answers

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

View Code

<a href="@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);                           
}
like image 152
Govinda Rajbhar Avatar answered Oct 18 '22 02:10

Govinda Rajbhar