From 18ab56fb25646e4f442ed1b3a3f04c8364602ef2 Mon Sep 17 00:00:00 2001 From: "liupo.wu" Date: Sat, 7 May 2022 14:47:32 +0800 Subject: [PATCH] feat: add ajax headers and post data --- README.md | 7 +++++-- src/FileSaver.js | 14 ++++++++++++-- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 8cf55b0f..901d87e1 100644 --- a/README.md +++ b/README.md @@ -60,10 +60,13 @@ import { saveAs } from 'file-saver'; ``` ```js -FileSaver saveAs(Blob/File/Url, optional DOMString filename, optional Object { autoBom }) +FileSaver saveAs(Blob/File/Url, optional DOMString filename, optional Object { autoBom, headers, postData }) ``` +Optional Object: -Pass `{ autoBom: true }` if you want FileSaver.js to automatically provide Unicode text encoding hints (see: [byte order mark](https://en.wikipedia.org/wiki/Byte_order_mark)). Note that this is only done if your blob type has `charset=utf-8` set. +- Pass `{ autoBom: true }` if you want FileSaver.js to automatically provide Unicode text encoding hints (see: [byte order mark](https://en.wikipedia.org/wiki/Byte_order_mark)). Note that this is only done if your blob type has `charset=utf-8` set. +- Pass `{ headers: object }` if you want append headers when fetch data from remote url. +- Pass `{ postData: object }` if you want send data when post data from remote url. Examples -------- diff --git a/src/FileSaver.js b/src/FileSaver.js index 5d204aee..73b99118 100644 --- a/src/FileSaver.js +++ b/src/FileSaver.js @@ -33,7 +33,6 @@ function bom (blob, opts) { function download (url, name, opts) { var xhr = new XMLHttpRequest() - xhr.open('GET', url) xhr.responseType = 'blob' xhr.onload = function () { saveAs(xhr.response, name, opts) @@ -41,7 +40,18 @@ function download (url, name, opts) { xhr.onerror = function () { console.error('could not download file') } - xhr.send() + if (opts && opts.headers) { + for (var key in opts.headers) { + xhr.setRequestHeader(key, opts.headers[key]) + } + } + if (opts && opts.postData) { + xhr.open('POST', url) + xhr.send(opts.postData) + } else { + xhr.open('GET', url) + xhr.send() + } } function corsEnabled (url) {