Handle file download from ajax post

前端 未结 20 2638
心在旅途
心在旅途 2020-11-21 05:46

I have a javascript app that sends ajax POST requests to a certain URL. Response might be a JSON string or it might be a file (as an attachment). I can easily detect Content

20条回答
  •  忘了有多久
    2020-11-21 06:21

    For those looking for a solution from an Angular perspective, this worked for me:

    $http.post(
      'url',
      {},
      {responseType: 'arraybuffer'}
    ).then(function (response) {
      var headers = response.headers();
      var blob = new Blob([response.data],{type:headers['content-type']});
      var link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = "Filename";
      link.click();
    });
    

提交回复
热议问题