簡體   English   中英

在Internet Explorer瀏覽器中從角度Blob打開PDF

[英]Opening PDF from angular blob in Internet explorer browser

我在Web API中有以下服務器端代碼

tempResponse = Request.CreateResponse(HttpStatusCode.OK);
tempResponse.Content = new StreamContent(stream);
tempResponse.Content.Headers.Add(@"Content-type", "application/pdf");
tempResponse.Content.Headers.ContentType = new   
System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
tempResponse.Content.Headers.ContentDisposition = new 
System.Net.Http.Headers.ContentDispositionHeaderValue("inline");

我正在使用有角JS,以下是我的JavaScript文件中的代碼。

$http.post(apiURL + "/DownloadPdf", data, { responseType: 'arraybuffer'}, config)
.then(function (result) {
  var file = new Blob([result.data], { type: 'application/pdf' })
  var fileName = "CommissionStatement.pdf"

  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.location.href = 'Assets/Document CheckList.pdf'
    window.navigator.msSaveOrOpenBlob(file, fileName)
  } else {
    var objectUrl = URL.createObjectURL(file)
    window.open(window.location.href = 'Assets/Document CheckList.pdf', '_blank')
    window.open(objectUrl, '_blank')

    $window.location.href =
      window.location.protocol + "//" +
      window.location.host + "?BrokerId=" +
      AgentInfo.Data.BrokerId +
      "&OfficeCode=" +
      AgentInfo.Data.OfficeCode;
  }
});

console.log($scope.Result)
},
function (error) {
  $scope.Error = error.data
})

這個Blob在Google Chrome和FireFox中可以正常打開。 但是IE會提示您打開或保存。 但我想在瀏覽器中打開它。 我會很感激在不提示的情況下將其打開。 謝謝

僅排除if / else語句並在IE中也打開ObjectURL怎么樣? 否則,如果要使用畫布在瀏覽器中呈現pdf.js,則可以使用pdf.js

我在您的代碼中看到的另一個問題是您正在嘗試使用window.open()打開一個新窗口,問題是它們很容易被阻止,除非它在用戶交互事件(例如onclick)發生后的1秒鍾內發生。 xhr.onload不是用戶交互事件

因此,如果您遇到類似的問題,請嘗試執行類似的操作

// Untested, just to give a ruffly idea
btn.onclick = () => {
  var win = window.open('', '_blank')
  win.document.body.innerHTML = 'loading...'
  $http.post(...).then(res => {
    var url = URL.createObjectURL(blob)
    // redirect
    win.location.href = url
  })
}

另一件事。 為什么要使用responseType = arrayBuffer 您可以直接將其設置為Blob ...?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM