Using Angular to upload a file via Ajax

I have a service that generates a CSV file and returns it to the page via http / ajax get. I would like the user to press a button, call a service call, and then upload the file to the user's browser.

I would like to do that. Angular Way, although I understand that this may have more to do with Ajax or the browser than Anuler itself.

The service is in C #, and this is what it returns:

return File(Encoding.UTF8.GetBytes(WriteCSV(assetList)), "text/csv", "results.csv"); 

The controller code that calls the service is as follows. It works, but I do not know what to do with success:

 $scope.exportCSV = function () { $http({ method: "get", url: "ExportCSV" }). error(function (data, status, headers, config) { alert("Error exporting data to CSV."); }); }; 
+4
source share
2 answers

You cannot initiate the download from a regular ajax GET or POST, you have to make a traditional way, for example window.location='url' , and set the correct HTTP header with the right type of content, which will prompt the download dialog to the users browser

+5
source

Perhaps a more β€œangular” way is for your controller to set a flag to start the download, but put the main functionality in the directive, which creates an element with the β€œdownload” attribute and is displayed, the callback / view calls ng-click.

For instance:

 // put this in a template related to a given controller <downloader ng-if="downloadready"></downloader> // controller just needs to trigger the directive into action module.controller(..., function($scope){ $scope.downloadready = true; // trigger the directive to be created }); // and the directive code will build the element and click the button module.directive('downloader', function ($compile) { return { restrict: 'E', replace: true, // values here can be placed in the template as variables and accessed in link() // but this is shortest to get the idea across template: '<a id="downloadbtn" class="btn" download="backup.json"></a>', link:function (scope, elm, attrs) { // this clicks the button outside the digest loop which the scope was updated in $timeout(function() { angular.element($('#downloadbtn')).triggerHandler('click'); }, 0); } } }); 

Although I admit that this is more crazy than changing the redirect to window.location.

+2
source

Source: https://habr.com/ru/post/1486624/


All Articles