Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC CSV File Download + Project Awesome

I'm currently using project awesome to pop a form which asks for an account number.

I take the number and generate a csv file and send it to the browser:

string billcsv = "account_ref,line1,line2,line3"

var VIRFile = File(new System.Text.UTF8Encoding().GetBytes(billcsv), "text/csv", "billfor" + accnumber+ ".csv")

return Json(VIRFile);

I would like the end user to prompted to save the csv file but cannot figure out who to.

Should I create the CSV file on disk first then pass the url to the file to the success function and use window.open(url) or is it possible to use javascript to recreate the file from the json result?

Json Result:

{"FileContents":[65,99,99,111,117,110,116,95,82,69,70,44,73,78,86,79,73,67,69,95,84,89,80,69,44,73,78,86,79,73,67,69,95,82,69,70,44,81,84,89,95,79,82,68,69,82,44,83,69,82,86,73,67,69,95,84,69,88,84,44,85,78,73,84,95,80,82,73,67,69,44,83,69,82,86,73,67,69,95,65,77,79,85,78,84,13,10,114,114,114,44,73,110,118,111,105,99,101,44,86,73,82,49,48,50,44,49,44,83,116,97,114,83,104,105,112,32,32,79,110,101,13,10,44,76,79,65,32,45,32,32,109,116,114,115,13,10,44,71,82,84,32,45,71,84,44,48,44,48,44,48,13,10,114,114,114,44,73,110,118,111,105,99,101,44,86,73,82,49,48,50,44,50,44,66,111,97,116,32,84,114,97,110,115,102,101,114,115,32,72,105,114,101,32,67,104,97,114,103,101,44,50,53,48,46,48,48,44,53,48,48,46,48,48,13,10,114,114,114,44,73,110,118,111,105,99,101,44,86,73,82,49,48,50,44,51,44,66,101,114,116,104,105,110,103,32,32,82,70,65,32,47,32,77,111,68,44,51,53,48,46,48,48,44,49,48,53,48,46,48,48,13,10],"ContentType":"text/csv","FileDownloadName":"billfor123.csv"}

like image 992
uk101man Avatar asked Jun 06 '11 10:06

uk101man


1 Answers

First of all don't use AJAX for downloading files. Use a normal form submission or an anchor pointing to the controller action which will serve the file. And then in the controller:

public ActionResult Download(string accnumber)
{
    string billcsv = "account_ref,line1,line2,line3";
    var data = Encoding.UTF8.GetBytes(billcsv);
    string filename = "billfor" + accnumber + ".csv";
    return File(data, "text/csv", filename);
}

Now in order to invoke this action and have the user be prompted for download simply create a link:

@Html.ActionLink("Download csv", "Download", new { accnumber = "123" })

or if you are using a form:

@Html.BeginForm("Download", "SomeController")
{
    @Html.TextBox("accnumber")
    <input type="submit" value="Download CSV" />
}
like image 165
Darin Dimitrov Avatar answered Oct 03 '22 07:10

Darin Dimitrov