Here's the relevant code:
Controller:
public ActionResult APIDownloadCSV()
{
var filename = Server.MapPath("~/xxx/test.csv");
byte[] content = System.IO.File.ReadAllBytes(filename);
return File(content, "text/csv", "test.csv");
}
Javascript:
var fetchCSV = function () {
return postDownloadCsv().then(function (data) {
var hiddenElement = document.createElement("a");
hiddenElement.href = "data:text/csv;charset=utf-8," + data;
hiddenElement.target = "_blank";
hiddenElement.download = "test.csv";
hiddenElement.click();
hiddenElement.remove();
});
}
postDownloadCSV
is just a simple one-line $http.post
function to the correct URL.
Problem:
When I use the above code, the file downloads as a CSV but returns only as a single continuous string. However, when I directly post the URL to the browser's location bar, the file being downloaded is correctly parsed. I've tried manipulating headers so that I'm requesting text/csv
but it's not working. For reasons, I must not employ a parser on the client-side to fix this (Not that I'd want to, anyway. The file is perfectly alright on the server. Just need to download it.)
I suppose the problem to be in the side of the client as I can download the file through the URL, but where? Am I doing something wrong with my $http.post
?
try to encode the href of the link before you set it.
hiddenElement.href = encodeURI("data:text/csv;charset=utf-8," + data);
working js-fiddle: http://jsfiddle.net/f6enw0L6/
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments