2017-07-24 120 views
0

因此,我使用PDF Sharp生成并保存在我的App_Data文件夹中的pdf。当用户单击我的控制器上的按钮时,我希望用户能够下载该文件。从web api控制器向角js提供文件

我设法让它工作(有点),因为用户可以下载文件,但是当他们打开这个pdf文件时,文档是空白的,看起来几乎是文件大小的两倍原始文件保存在我的App_Data文件夹中。我不确定发生了什么问题,但只能猜测这与我如何读取文件和流式传输数据有关。

反正这是Web API控制器功能:

[HttpGet] 
public HttpResponseMessage DownloadPdf(int itemId) 
{ 
    var item = _myService.GetItem(itemId); 
    var result = Request.CreateResponse(HttpStatusCode.OK); 

    result.Content = new StreamContent(File.ReadAllBytes(HostingEnvironment.MapPath(item.ReportFilePath))); 
    result.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/pdf"); 
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); 
    result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(HostingEnvironment.MapPath(item.ReportFilePath)); 

    return result; 
} 

,这是我的角度控制器上的相关功能(注意businessResource呼叫只是通过$ HTTP调用的数据路由到我的web api函数) :

$scope.downloadPdf = function() { 
    businessResource.downloadPdf($scope.itemId).then(function (response) { 
     var headers = response.headers; 
     var filename; 
     var disposition = headers('Content-Disposition'); 
     if (disposition && disposition.indexOf('attachment') !== -1) { 
      var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; 
      var matches = filenameRegex.exec(disposition); 
      if (matches != null && matches[1]) { 
       filename = matches[1].replace(/['"]/g, ''); 
      } 
     } 

     // Get the blob url creator 
     var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL; 
       if (urlCreator) { 
        var link = document.createElement('a'); 

        if ('download' in link) { 

         // Prepare a blob URL 
         var blob = new Blob([response.data], { type: headers('content-type') }); 
         var url = urlCreator.createObjectURL(blob); 
         link.setAttribute('href', url); 
         link.setAttribute("download", filename); 

         // Simulate clicking the download link 
         var event = document.createEvent('MouseEvents'); 
         event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null); 
         link.dispatchEvent(event); 

        } 
       } 
      }, function (response) { 
       notificationsService.error("Error", "Could not generate report"); 
      }); 
     } 

所以我只想澄清:呼叫在这个意义上的工作,我得到一个PDF文件下载,但该文件没有包含任何内容,当我在浏览器/ PDF阅读器中打开它,几乎是是我存储的原始文件大小的两倍App_Data文件夹。

我不知道数据在哪里被破坏..任何想法?

回答

0

想通了:

return $http.get('<end point url>); 

到:

的$ http.get这是使得调用所需的网络API来改变

return $http.get('<end point url>', { responseType: 'arraybuffer' }); 

即。 responseType需要设置为'arraybuffer'。希望这可以帮助别人!