neethu neethu - 4 months ago 97
C# Question

File download not working in asp.net mvc 4

I am new to mvc4 . I used the below code to download file from server to client in the controller:

public ActionResult IndexSpecification(int option_id)
{
int cat = (int)Session["category_Name"];
int prod = (int)Session["product_ID"];
int user = (int)Session["logged_in"];
string twoinone = cat + "_" + prod;
f1 = Download(twoinone);
return f1;
}


where Download function is:

public FileResult Download( string twoinone)
{
var webClient = new WebClient();
byte[] fileBytes = System.IO.File.ReadAllBytes(Path.Combine(Server.MapPath("~/Download"), "a.rar"));
string fileName = "Tellersoft.rar";
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}


The call to the controller is from ajax :

$.ajax({
type: "POST",
url: base_url + '/Options/IndexSpecification',
data: { option_id : 2 },
//dataType: 'json', encode: true,
async: false,
cache: false,
success: function (data, status, jqXHR) {
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
if (typeof (console) != 'undefined') {
alert("oooppss");
} else {
alert("something went wrong");
}
}
});


But downloading not working .not even returning any error. Please help

Answer

Try this way

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

2 . Controller

public FileActionResult Downloads() 
{
    var dir = new System.IO.DirectoryInfo(Server.MapPath("~/App_Data/Images/"));
    System.IO.FileInfo[] fileNames = dir.GetFiles("*.*");            
    List<string> items = new List<string>();

    foreach (var file in fileNames)
    {
        items.Add(file.Name);                
    }

    return View(items);           
}

View

@model List<string>

<h2>Downloads</h2>
<table>
    <tr>
        <th>File Name</th>
        <th>Link</th>
    </tr>
    @for (var i =0; i <= Model.Count -1; i++) {
        <tr>
            <td>
                @Model[i].ToString()
            </td>
            <td>     
                @Html.ActionLink("Download", "Download", new  { ImageName=@Model[i].ToString() })           
            </td>
        </tr>
    }
</table>