developer tip

Angular의 서버에서 텍스트 / csv 콘텐츠를 파일로 다운로드

copycodes 2021. 1. 5. 08:13
반응형

Angular의 서버에서 텍스트 / csv 콘텐츠를 파일로 다운로드


csvnode.js 서버에서 파일 을 스트리밍하려고 합니다. 서버 부분은 매우 간단합니다.

server.get('/orders' function(req, res) {
  res.setHeader('content-type', 'text/csv');
  res.setHeader('content-disposition', 'attachment; filename='orders.csv');
  return orders.pipe(res); // assuming orders is a csv file readable stream (doesn't have to be a stream, can be a normal response)
}

내 각도 컨트롤러에서 다음과 같이하려고합니다.

$scope.csv = function() {
    $http({method: 'GET', url: '/orders'});
};

이 함수는 ng-click내보기에서 버튼을 클릭 할 때 호출됩니다 .

<button ng-click="csv()">.csv</button>

Angular의 서버에서 파일을 다운로드하는 방법에 대한 다른 답변을 살펴 보았지만 저에게 맞는 것을 찾지 못했습니다. 이 작업을 수행하는 일반적인 방법이 있습니까? 단순해야 할 것 같습니다.


$http서비스는 promise아래와 같이 두 개의 콜백 메서드가있는를 반환 합니다.

$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) {
    // handle error
  });

이 문제 에 대한 웹상 의 대부분의 참조는 ajax 호출 '즉시'를 통해 파일을 다운로드 할 수 없다는 사실을 지적합니다. 관련된 ( iframes해 키시) 솔루션과 @dcodesmith와 같은 솔루션이 작동하고 완벽하게 실행되는 것을 보았습니다.

Angular에서 작동하고 매우 격렬한 또 다른 솔루션이 있습니다.

에서 보기 , 랩 csv과 다운로드 버튼 <a>태그 다음과 같은 방법을 :

<a target="_self" ng-href="{{csv_link}}">
  <button>download csv</button>
</a>

( 여기target="_self 에 ng-app 내에서 Angular의 라우팅을 비활성화하는 것이 중요합니다 . )

컨트롤러csv_link에서 다음과 같은 방법을 정의 할 수 있습니다 .

$scope.csv_link = '/orders' + $window.location.search;

( $window.location.search선택 사항이며 서버에 추가 검색 쿼리를 전달하려는 경우 onlt)

이제 버튼을 클릭 할 때마다 다운로드가 시작됩니다.


var anchor = angular.element('<a/>');
anchor.css({display: 'none'}); // Make sure it's not visible
angular.element(document.body).append(anchor); // Attach to document

anchor.attr({
    href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
    target: '_blank',
    download: 'filename.csv'
})[0].click();

anchor.remove(); // Clean it up afterwards

이 코드는 Mozilla와 Chrome 모두에서 작동합니다.


이것이 IE 11+, Firefox 및 Chrome에서 저에게 효과적이었습니다. 사파리에서는 파일을 다운로드하지만 알 수 없으며 파일 이름이 설정되지 않았습니다.

if (window.navigator.msSaveOrOpenBlob) {
    var blob = new Blob([csvDataString]);  //csv data string as an array.
    // IE hack; see http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx
    window.navigator.msSaveBlob(blob, fileName);
} else {
    var anchor = angular.element('<a/>');
    anchor.css({display: 'none'}); // Make sure it's not visible
    angular.element(document.body).append(anchor); // Attach to document for FireFox

    anchor.attr({
        href: 'data:attachment/csv;charset=utf-8,' + encodeURI(csvDataString),
        target: '_blank',
        download: fileName
})[0].click();
anchor.remove();
}

각도 1.5.9 사용

window.location을 csv 파일 다운로드 URL로 설정하여 이와 같이 작동하도록 만들었습니다. 최신 버전의 Chrome 및 IE11에서 테스트 및 작동합니다.

모난

   $scope.downloadStats = function downloadStats{
        var csvFileRoute = '/stats/download';
        $window.location = url;
    }

HTML

<a target="_self" ng-click="downloadStats()"><i class="fa fa-download"></i> CSV</a>

에서 PHP 하여 응답 헤더 이하로 설정 :

$headers = [
    'content-type'              => 'text/csv',
    'Content-Disposition'       => 'attachment; filename="export.csv"',
    'Cache-control'             => 'private, must-revalidate, post-check=0, pre-check=0',
    'Content-transfer-encoding' => 'binary',
    'Expires' => '0',
    'Pragma' => 'public',
];

참조 URL : https://stackoverflow.com/questions/20904151/download-text-csv-content-as-files-from-server-in-angular

반응형