通过jQuery下载八位字节流

通过jQuery下载八位字节流

本文介绍了通过jQuery下载八位字节流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了以下代码:

I have implemented the following code:

我有一个类似这样的html按钮:

I have an html button like this:

HTML

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

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

The downCont() function invoked on click is an ajax POST like this:

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触发浏览器本身下载存档?

Now, the response of this POST request is used to download an archive of images which is streamed directly to the user (content-type: application/octet-stream). How can I trigger the download of the archive by the browser itself using jQuery?

推荐答案

您需要根据数据 Blob ,并将其添加到href中并触发点击.

You need to create a url from a data Blob, and add it to an href and trigger a click.

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);
    }

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

因此,此函数将处理您的数据并执行这两个步骤,您可以使用如下所示的方法:

So this function will take your data and perform those two steps, and you can use it something like this:

$.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编码的数据字符串来实现.还要注意,我提供的功能使用箭头功能和默认的args,但是如果需要,可以很容易地对其进行ES5'修改.

Note that for obsolete browsers which don't support Blobs there is also an alternate way to do it with window.open using a base64 encoded data string. Also note the function I provided uses arrow functions and default args, but it's easy to ES5'ify it if you want to.

这篇关于通过jQuery下载八位字节流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 19:35