2017-02-09 56 views
1

我想從服務器下載pdf文件並在瀏覽器中顯示它。我使用的web api方法將該文件作爲httpResponseMessage返回,並且工作正常,因爲它返回文件。但在AngularJs方面,我無法顯示該文件。有人能幫我理解我錯過了什麼嗎?使用angularjs顯示pdf

的Web API方法:

public HttpResponseMessage GetHelpReferenceDocs(Guid streamKey) 
    { 
     var fakeFileName = GetStream(streamKey); // If this succeeds, stream is known and unexpired. 

     // Internal file name 
     string staticFileName = helpFiles[fakeFileName]; 

     var mappedPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Static/" + staticFileName); 

     HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); 
     var stream = new FileStream(mappedPath, FileMode.Open, FileAccess.Read, FileShare.Read); 

     result.Content = new StreamContent(stream); 
     result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); 
     result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(mappedPath); 
     result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); 
     result.Content.Headers.ContentLength = stream.Length; 
     return result; 


    } 

AngularJS:

function loadDocument(fileName) { 

     REST.post(commonService.constants.webapi.helpFileStreamKey + fileName) 
     .then(function(response) { 
      var streamGuid = response.data; 

      REST.get(commonService.constants.webapi.helpReferenceGuide + streamGuid).then(function (response) { 

      $window.open(response.data); 

      }); 

      }) 
     .catch(function (e) { $scope.errorHandler(moduleName, e); }) 
     .finally($scope.waitOn); 
    } 

回答

0

好吧,我找到了解決方案。需要修改我的Angular代碼,它工作得很好。這裏是代碼,如果有人面臨同樣的問題:

function loadDocument(fileName) { 

     REST.post(commonService.constants.webapi.helpFileStreamKey + 'firmUserGuid') 
     .then(function(response) { 
      var streamGuid = response.data; 

      REST.get(commonService.constants.webapi.helpReferenceGuide + streamGuid).then(function (response) { 
       var pdfFileURL = response.config.url; 
       $window.open(pdfFileURL); 

      }); 

      }) 
     .catch(function (e) { $scope.errorHandler(moduleName, e); }) 
     .finally($scope.waitOn); 
    } 
0

在建議here看看,或者你可以專門嘗試的NPM模塊用於顯示PDF文檔,其中本已經照顧你了,such as this one.