How can I call the MVC FileContentResult JQuery and make it ask the user to save the return on it?
I am creating a CSV from an MVC 3 website and using FileContentResult to pass this to the user. This worked great, but it took 30 seconds to generate the csv and therefore 30 seconds before the user was prompted to save the query.
public virtual FileContentResult GetSpreadsheet(string id)
{
var service = new SpreadsheetService();
var result = service.GetCSV();
return File(new System.Text.UTF8Encoding().GetBytes(result.Message), "text/csv", "Report123.csv");
}
So, I thought I'd just call via JQuery, but this (no surprise!) Just dumps the CSV to the page.
$.post("/Home/GetSpreadsheet/" + id, null, function (data) {
$('#resultDiv').html(data);
});
Does anyone know how I will generate a prompt to save, now I have the data? Thanks to
source to share
You cannot do this. Forget it. Unable to upload files using AJAX. In fact, the AJAX call will work, you will be taken to the server, the server will send the content of the file back to the client, the AJAX success callback will be called and passed as an argument the content of the file and where it ends for you. Using javascript, for obvious reasons, you cannot directly save the file to the client computer, and you cannot prompt for the Save As dialog.
So instead of using AJAX, just create a binding:
@Html.ActionLink("download spreadsheet", "GetSpreadsheet", new { id = "123" })
Now, if the server has set the header Content-Disposition
to attachment
, the browser will prompt the user to download and save the file to the selected location on their computer.
source to share
If you don't want to use anchor use a hidden iframe and set the src of the iframe to the url of the file you upload.
<iframe id="hiddenFrame" src="" style="display:none; visibility:hidden;"></iframe>
Instead of using the $ .post (...) 'line:
downloadSpreadsheet('123');
function downloadSpreadsheet(id) {
var url = '@Url.Content("~/YourControllerName/GetSpreadsheet")' + "?id=" + id;
$('#hiddenFrame').attr('src', url);
}
Or you can try jQuery Plugin to request Ajax files Upload files
Using the plugin, you can download by clicking:
jQuery.download(url, data, method)
source to share