3

我正在将 Intranet 与文档管理系统集成。DMS 有一个 SOAP API。我们构建了一个接收 REST 调用、发出 SOAP 调用并返回 JSON 或文档数据的客户端。

问题是 AJAX 文件下载的所有解决方案似乎都使​​用 iFrame(请参阅John Culniver 的文件下载插件)。

我不能使用它,因为我需要在标头中提供身份验证凭据。我能想到的唯一其他潜在解决方案是使用window.open(如果我可以通过浏览器弹出窗口阻止)。

有没有人有另一种潜在的解决方案,或者如何用 window.open 做到这一点?

谢谢

4

2 回答 2

3

我认为这个问题没有客户端解决方案。window.open不会让您设置请求标头。您需要执行一些操作,例如向服务器发送 cookie 或其他值,并添加服务器端代码以减轻对请求标头的需求。

请参阅以下问题的答案:

于 2013-03-17T20:10:08.693 回答
1

我能够成功地做到这一点。我是我的示例,我使用的是基本身份验证,但是您可以将Authorization标头替换为不同的值(例如,您可以将其替换为Bearer Yourtokenvalue.

这是代码片段

$(document).on("click", "#btn", function() {

  var username = "yourUserNameForBasicAuthentication";
  var password = "yourPasswordForBasicAuthentication"

  console.log("button clicked");
  var request = new XMLHttpRequest();
  request.open("GET", $("#txtUrl").val().trim(), true);

  //Set the authorization headers
  request.setRequestHeader("Authorization", "Basic " + window.btoa(username + ":" + password));

  //Set the Response type as blob which means raw data
  request.responseType = "blob";

  //We will initiate a default file name in case no file name is detected later on from headers of HTTP Request
  var fileName = "unnamed.pdf";
  request.onload = function(event) {
    if (request.status == 200) {
      console.log("success response received");
      var blob = request.response;

      //Getting contenttype from response headers
      var contentType = request.getResponseHeader("content-type");
      if (contentType == null) {
        contentType = "application/pdf";
      }

      //Check 'Content-Disposition' header to get filename of file (if possible)
      if (request.getResponseHeader("Content-Disposition")) {
        var contentDisposition = request.getResponseHeader("Content-Disposition");
        fileName = contentDisposition.substring(contentType.indexOf("=") + 1);
      }

      if (window.navigator.msSaveOrOpenBlob) {
        // Internet Explorer
        window.navigator.msSaveOrOpenBlob(new Blob([blob], {
          type: contentType
        }), fileName);
      } else {
        var el = document.createElement("a");
        document.body.appendChild(el);
        el.href = window.URL.createObjectURL(blob);
        el.download = fileName;
        el.click();
        el.remove();
        window.URL.revokeObjectURL(el.href);
      }


    } //end of Status code
    else {
      alert("System failed to authenticate");
    }

  } //End of event
  request.send();

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="https://yoursamplefile.txt" id="txtUrl" style="width:100%" /><br />
<input type='button' value='Download File' id='btn' />

于 2019-11-20T11:16:07.377 回答