使用Angular

时间:2016-04-05 20:52:36

标签: angularjs pdf asp.net-web-api download content-type

我正在尝试使用Angular从WebApi下载PDF,但文件只有15个字节。如果我记录从WebApi接收的数据,它是一个具有预期大小

的数组缓冲区

WebApi

    [HttpGet]
    public HttpResponseMessage MatchRegistrationReport(int matchId)
    {
        try
        {
            var gen = new MSReports.Components.MatchRegistration();
            byte[] bytes = gen.GeneratePDF(matchId, 10);
            var stream = new MemoryStream(bytes);

            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(stream)
                //Content = new ByteArrayContent(bytes)
            };
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = gen.ReportName + ".pdf"
            };
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
            return result;
        }
        catch (Exception ex)
        {
            Log.Error(ex.Message);
            return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
        }
    }

角度控制器

$scope.Print = function () {
    $scope.message = "Downloading";
    reportResource.printMatchRegistration($scope.match.Id).then(function (data, status, headers, config) {
        var file = new Blob([data], {
            type: 'application/csv'
        });
        //trick to download store a file having its URL
        var fileURL = URL.createObjectURL(file);
        var a = document.createElement('a');
        a.href = fileURL;
        a.target = '_blank';
        a.download = 'MatchRegistration.pdf';
        document.body.appendChild(a);
        a.click();
        //$scope.message = "Completed";
    }, function (data, status, headers, config) {
        $scope.message = "A error occurred";
    });
}

和资源

printMatchRegistration: function (matchId) {
  return $http({
  method: 'get',
  url: this.getApiPath() + "MatchRegistrationReport?matchId=" + matchId,
  headers: {
      'Content-type': 'application/pdf',
  },
  responseType: 'arraybuffer'
});

我认为它与内容类型有关,但可以“弄清楚是什么。”

1 个答案:

答案 0 :(得分:2)

你刚刚找到答案

更改为

reportResource.printMatchRegistration($scope.match.Id).then(function (response) {
    var file = new Blob([response.data], {
        type: 'application/pdf'
    });

和这个

        printMatchRegistration: function (matchId) {
            var data = { 'matchId': matchId };
            return $http({
                method: 'get',
                url: this.getApiPath() + "MatchRegistrationReport",
                params: data,
                headers: {
                    'Content-type': 'application/pdf',
                },
                responseType: 'arraybuffer'
            });
        },