通过 jQuery 下载八位字节流

2024-03-24

我已经实现了以下代码:

我有一个像这样的 html 按钮:

HTML

<button style="background-color: #f39900;" onclick="downCont()">
    Download all content
</button>

The downCont()单击时调用的函数是ajax POST像这样:

JQuery

var downCont = function() {
          $.ajax({
              method: "POST",
              contentType: "application/x-www-form-urlencoded",
              url: "<endpoint here>",
              data: {
                "tokenId": token,
                "downloadId": "cz98567354",
                "saveAs": "AllContents"
              }
            })
            .done(function() {
              alert("I have downloaded all contents!");
            });
        });

现在,对此的回应POST请求用于下载图像档案,该图像档案直接流式传输给用户(content-type: application/octet-stream)。如何使用浏览器本身触发存档的下载jQuery?


您需要从数据创建一个 urlBlob https://developer.mozilla.org/en/docs/Web/API/Blob,并将其添加到 href 并触发点击。

let url;

const saveData = (() => {
  const a = document.createElement('a');
  a.style = 'display: none';
  document.body.appendChild(a);

  return (data, fileName, type = 'octet/stream') => {
    const blob = new Blob([data], { type });

    if (navigator.msSaveBlob) {
      return navigator.msSaveBlob(blob, fileName);
    }

    if (url) {
      // Keep at most 1 blob around by removing the last used one.
      URL.revokeObjectURL(url);
    }

    url = URL.createObjectURL(blob);
    a.href = url;
    a.download = fileName;
    a.click();
    return true;
  };
})();

因此,这个函数将获取您的数据并执行这两个步骤,您可以像这样使用它:

$.ajax({
  method: "POST",
  contentType: "application/x-www-form-urlencoded",
  url: "<endpoint here>",
  data: {
    "tokenId": token,
    "downloadId": "cz98567354",
    "saveAs": "AllContents"
  }
})
.done((data) => saveData(data, 'myDownload.zip'));

请注意,对于不支持 Blob 的过时浏览器,还有另一种方法可以使用window.open使用 Base64 编码的数据字符串。另请注意,我提供的函数使用箭头函数和默认参数,但如果您愿意,可以很容易地对其进行 ES5 化。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 jQuery 下载八位字节流 的相关文章

随机推荐