Reputation: 1249
Edit:
html file:
<button data-ng-click="$ctrl.toCSV()">ToCSV</button>
code in controller:
$scope.toCSV = function () {
var sampleJson = {"key1": ["val1", "val2"], "key2": "valKey2", "key3": "valKey3"};
// the service forms and returns the url string
var url = vm.originUrl + sampleService.getCSVDetails(id, false, "csv").url;
var form = $('<form action="' + url + '" method="post" style="display:none;">' +
'<input type="text/json" name="jsonData" value="' + sampleJson + '" />' + '</form>');
$('body').append(form);
form.submit();
};
I am not able to understand where I could be going wrong, I checked a lot of solutions posted. The response that I am getting when I pass the same using postman is:
cache-control →no-store, no-cache=set-cookie
content-disposition →attachment; filename=SampleDetails.csv
content-encoding →gzip
content-language →en-US
content-length →767
content-type →application/octet-stream
date →Wed, 25 Oct 2017 15:13:51 GMT
expires →Thu, 01 Dec 1994 16:00:00 GMT
pragma →no-cache
x-frame-options →SAMEORIGIN
x-powered-by →Servlet/3.1
I am just not sure how to set this up so that the it gets downloaded in the browser on clicking the text 'ToCSV'. Right now it just open in a new blank page instead of download, although in postman I am able to get the content of the file.
Any suggestions how to bundle the json data and hit the URL via post method...?
Thanks!
Upvotes: 0
Views: 4176
Reputation: 11
I used file-saver to download my pdf files.
function downloadPdf(id) {
myServiceToGetFile(id).then(function(response) {
var blob = new Blob([response.data], { type: "application/octet-stream"});
//change download.pdf to the name of whatever you want your file to be
fileSaver.saveAs(blob, 'fileName.pdf');
}
}
and the service looks like this:
function myServiceToGetFile(id) {
return $http.get(
baseUrl + '/link/to/pdf/' + id,
{responseType: "arraybuffer"}); // must add this to work
}
PS: We had to put the library in a service, because of some minification issues.
Upvotes: 1