下载示例

注意:该方法仅适用于浏览器端,兼容 IE10+ 和现代浏览器。

点击查看文档

Plain Text

text string

utilHelpers.download("hello world Ò", {
  fileName: "text-string.txt",
  type: "text/plain"
});

text dataURL

utilHelpers.download("data:text/plain,hello%20world", {
  fileName: "text-dataurl.txt",
  type: "text/plain"
});

text blob

utilHelpers.download(new Blob(["hello world"]), {
  fileName: "text-blob.txt",
  type: "text/plain"
});

text url

utilHelpers.download("./test.txt", { dataType: "url" });

text UInt8 Array

var str = "hello world",
    arr = new Uint8Array(str.length);
str.split("").forEach(function (s, i) {
  arr[i] = str.charCodeAt(i);
});
utilHelpers.download(arr, "text-uint8.txt");

HTML

html string

utilHelpers.download(document.documentElement.outerHTML, {
  fileName: "html-string.html",
  type: "text/html"
});

html Blob

utilHelpers.download(new Blob(["hello world".bold()]), {
  fileName: "html-blob.html",
  type: "text/html"
});

ajax callback

var xhr = new XMLHttpRequest();
xhr.open("GET", "./index.html");
xhr.responseType = "blob";
xhr.onload = function (e) {
  utilHelpers.download(e.target.response, {
    fileName: "html-ajax.html",
    type: "text/html"
  });
};
xhr.send();

// utilHelpers.download('./index.html', { dataType: 'url' });

Binary Files

image from URL

utilHelpers.download("./test.jpeg", { dataType: "url" });

Image via ajax from custom filename

var xhr = new XMLHttpRequest();
xhr.open("GET", "./test.jpeg");
xhr.responseType = "blob";
xhr.onload = function (e) {
  utilHelpers.download(e.target.response, "image-ajax.jpg");
};
xhr.send();

word

utilHelpers.download("./test.docx", { dataType: "url" });

excel

utilHelpers.download("./test.xlsx", { dataType: "url" });

pdf

utilHelpers.download("./test.pdf", { dataType: "url" });

mp3

utilHelpers.download("./test.mp3", { dataType: "url" });

mp4

utilHelpers.download("./test.mp4", { dataType: "url" });

zip

utilHelpers.download("./test.zip", { dataType: "url" });