Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download a file from http response body

I've been researching this for quite a while now, and can't find a clear answer / a way to solve my problem.

The situation is this: I'm sending a post request to a server. The response contains the binary of a pcap file in it's body. How do I download it as a file.

My simplified code:

...
this.downloadPcap = function(timestamp){
  var start = timestamp-10;
  var end = timestamp+10;
  var requestData = {"start": start, "end": end};
  $http.post(serverUrl, requestData);
}

This is triggered by a click, where I get the timestamp of some event, and the server creates a PCAP file from 10 seconds before and after the exact event.

I receive a response with a long binary. Also:

Content-Length: 134772

Content-Type: application/pcap

Now I was told that if the header will be like so, the browser will automatically start downloading the response as a file. It doesn't.

So I've read very little about Blob, and FileSaver, but I feel like there must be an easier way to download files that are being created dynamically.

Can someone please point me in some direction? Is there no simpler way than including more libraries?

Thanks in advance

like image 805
Finkel Avatar asked Dec 31 '15 12:12

Finkel


1 Answers

beaver pointed me to the answer here: https://stackoverflow.com/a/20904398/5459561

Works perfectly! I'm personally downloading a PCAP, and the encoding is different, but all the rest works!

$http service returns a promise which has two callback methods as shown below.

$http({method: 'GET', url: '/someUrl'}).
  success(function(data, status, headers, config) {
     var anchor = angular.element('<a/>');
     anchor.attr({
         href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
         target: '_blank',
         download: 'filename.csv'
     })[0].click();

  }).
  error(function(data, status, headers, config) {
    // if there's an error you should see it here
  });
like image 55
Finkel Avatar answered Oct 15 '22 00:10

Finkel