I'm trying to download an excel CSV file using jquery's $.post method but I'm having trouble getting it to work.
I can see that the server is creating the file and sending it back to the client but after that, I can't get the file to actually download.
My jquery post function looks like this:
$.post("/GenerateFile", { id: id, startDate: startDate, endDate: endDate }, function (data) {
window.location = data;
}).fail(function (XMLHttpRequest, textStatus, errorThrown) {
});
And my server side function looks like this:
public async Task<ActionResult> GenerateFile(string id, string startDate, string endDate)
{
try
{
// My logic to create the file here, this is of type Task<MemoryStream>
var outputFile = await CreateFile(sDate, eDate);
return File(outputFile, "text/comma-separated-values", "Download.csv");
}
catch (Exception e)
{
return new HttpStatusCodeResult(400, e.Message);
}
}
When this data comes back to the client, it tries to navigate to a new page using the data from the CSV file (as can be seen on the URL link) with the message
Bad Request - Invalid URL
HTTP Error 400. The request URL is invalid.
There is no problem with the file generation itself as I can create the file locally onto disk, it's just when I'm trying to use a browser to download it.
I've seen guides which show this method working but there seems to be something that I'm missing that's stopping the download from working.