0

I need to download a file from an ajax GET request in angularjs (the ajax query redirects to the download link). My current approach is to make an invisible iframe and load that url in it so as to get the "Save as" popup for the downloaded file. But I need to change the name of the file before the save as popup.

Please suggest a way to achieve the same.

Rahul
  • 91
  • 1
  • 8
  • the file name will be as defined by the server you'll need to send a `content-disposition` header to change it. See http://stackoverflow.com/questions/1012437/uses-of-content-disposition-in-an-http-response-header – andrew Aug 31 '15 at 12:24
  • the link is of Amazon S3 resource. Is there a way to change the fileName at client side instead of server? – Rahul Aug 31 '15 at 13:27
  • 1
    I doubt it. it might be possible to read the data using a js `FileReader` and save using `blob` but I suspect if you get anything working It won't work well in all browsers. look at this: http://stackoverflow.com/questions/13405129/javascript-create-and-save-file – andrew Aug 31 '15 at 14:16

1 Answers1

0

You can use Filesaver.js script written by eligrey(Im using angularjs in the example here) You can achieve the same in classic javascript using XmlHttpRequest object

//In your html code , add these : ->
<script src="https://rawgit.com/eligrey/FileSaver.js/master/FileSaver.js" type="text/javascript"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
//In your Javascript:- 

$http({
    url: "url where the file is located",
    method: "GET",
    responseType: "blob"
}).then(function (response) {

saveAs(response.data,"newfilename.extension");

})    
Vibhu
  • 536
  • 1
  • 3
  • 11