从角度js的web api下载csv文件

时间:2013-11-30 12:58:58

标签: javascript angularjs csv asp.net-web-api httpresponse

我的API控制器正在返回一个csv文件,如下所示:

    [HttpPost]
    public HttpResponseMessage GenerateCSV(FieldParameters fieldParams)
    {
        var output = new byte[] { };
        if (fieldParams!= null)
        {
            using (var stream = new MemoryStream())
            {
                this.SerializeSetting(fieldParams, stream);
                stream.Flush();
                output = stream.ToArray();
            }
        }
        var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(output) };
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "File.csv"
        };
        return result;
    }

以及发送和接收csv文件的angularjs如下所示:

$scope.save = function () {
            var csvInput= extractDetails();

            // File is an angular resource. We call its save method here which
            // accesses the api above which should return the content of csv
            File.save(csvInput, function (content) {
                var dataUrl = 'data:text/csv;utf-8,' + encodeURI(content);
                var hiddenElement = document.createElement('a');
                hiddenElement.setAttribute('href', dataUrl);
                hiddenElement.click();
            });
        };

在chrome中,它会下载一个名为document但没有文件类型扩展名的文件。 该文件的内容为[Object object]

在IE10中,没有下载任何内容。

我该怎么做才能解决这个问题?

更新: 对于那些有同样问题的人来说,这可能会有用:link

10 个答案:

答案 0 :(得分:62)

尝试如下:

File.save(csvInput, function (content) {
    var hiddenElement = document.createElement('a');

    hiddenElement.href = 'data:attachment/csv,' + encodeURI(content);
    hiddenElement.target = '_blank';
    hiddenElement.download = 'myFile.csv';
    hiddenElement.click();
});

基于this question

中最优秀的答案

答案 1 :(得分:9)

我使用了以下解决方案,它对我有用。



 if (window.navigator.msSaveOrOpenBlob) {
   var blob = new Blob([decodeURIComponent(encodeURI(result.data))], {
     type: "text/csv;charset=utf-8;"
   });
   navigator.msSaveBlob(blob, 'filename.csv');
 } else {
   var a = document.createElement('a');
   a.href = 'data:attachment/csv;charset=utf-8,' + encodeURI(result.data);
   a.target = '_blank';
   a.download = 'filename.csv';
   document.body.appendChild(a);
   a.click();
 }




答案 2 :(得分:4)

最后一个答案对我有用了几个月,然后停止识别文件名,正如adeneo评论的那样......

@ Scott在这里的回答对我有用:

Download file from an ASP.NET Web API method using AngularJS

答案 3 :(得分:4)

在Chrome 42中没有一个适合我的工作......

相反,我的指令现在使用此link函数(base64使其有效):

  link: function(scope, element, attrs) {
    var downloadFile = function downloadFile() {
      var filename = scope.getFilename();
      var link = angular.element('<a/>');
      link.attr({
        href: 'data:attachment/csv;base64,' + encodeURI($window.btoa(scope.csv)),
        target: '_blank',
        download: filename
      })[0].click();
      $timeout(function(){
        link.remove();
      }, 50);
    };

    element.bind('click', function(e) {
      scope.buildCSV().then(function(csv) {
        downloadFile();
      });
      scope.$apply();
    });
  }

答案 4 :(得分:2)

我最近必须实现这一点。想分享我想到的东西;

为了让它在Safari中运行,我必须设置目标:'_ self',。不要担心Safari中的文件名。看起来像这里提到的那样不受支持; https://github.com/konklone/json/issues/56http://caniuse.com/#search=download

以下代码适用于Mozilla,Chrome&amp; Safari浏览器;

  var anchor = angular.element('<a/>');
  anchor.css({display: 'none'});
  angular.element(document.body).append(anchor);
  anchor.attr({
    href: 'data:attachment/csv;charset=utf-8,' + encodeURIComponent(data),
    target: '_self',
    download: 'data.csv'
  })[0].click();
  anchor.remove();

答案 5 :(得分:1)

使用html表单,而不是使用Ajax / XMLHttpRequest / $ http来调用WebApi方法。这样浏览器就会使用响应标头中的文件名和内容类型信息来保存文件,并且您不需要解决javascript对文件处理的限制。您可能还使用GET方法而不是POST,因为该方法返回数据。以下是一个示例表单:

<form name="export" action="/MyController/Export" method="get" novalidate>
    <input name="id" type="id" ng-model="id" placeholder="ID" />
    <input name="fileName" type="text" ng-model="filename" placeholder="file name" required />
    <span class="error" ng-show="export.fileName.$error.required">Filename is required!</span>
    <button type="submit" ng-disabled="export.$invalid">Export</button>
</form>

答案 6 :(得分:1)

在Angular 1.5中,使用$window服务下载文件。

angular.module('app.csv').factory('csvService', csvService);

csvService.$inject = ['$window'];

function csvService($window) {
    function downloadCSV(urlToCSV) {
        $window.location = urlToCSV;
    }
}

答案 7 :(得分:0)

IE不支持a.download。至少在HTML5“支持”页面。 :(

答案 8 :(得分:0)

I think the best way to download any file generated by REST call is to use window.location example :

    $http({
        url: url,
        method: 'GET'
    })
    .then(function scb(response) {
        var dataResponse = response.data;
        //if response.data for example is : localhost/export/data.csv
        
        //the following will download the file without changing the current page location
        window.location = 'http://'+ response.data
    }, function(response) {
      showWarningNotification($filter('translate')("global.errorGetDataServer"));
    });

答案 9 :(得分:0)

可行的解决方案:

downloadCSV(data){   
 const newBlob = new Blob([decodeURIComponent(encodeURI(data))], { type: 'text/csv;charset=utf-8;' });

        // IE doesn't allow using a blob object directly as link href
        // instead it is necessary to use msSaveOrOpenBlob
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          window.navigator.msSaveOrOpenBlob(newBlob);
          return;
        }

        // For other browsers:
        // Create a link pointing to the ObjectURL containing the blob.
        const fileData = window.URL.createObjectURL(newBlob);

        const link = document.createElement('a');
        link.href = fileData;
        link.download = `Usecase-Unprocessed.csv`;
        // this is necessary as link.click() does not work on the latest firefox
        link.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));

        setTimeout(function () {
          // For Firefox it is necessary to delay revoking the ObjectURL
          window.URL.revokeObjectURL(fileData);
          link.remove();
        }, 5000);
  }