use-downloads
Version:
A js utilities that contains all the methods for downloading files
100 lines (93 loc) • 2.85 kB
JavaScript
/*!
* use-downloads v1.5.1
* A js utilities that contains all the methods for downloading files
* (c) 2022-2023 saqqdy<https://github.com/saqqdy>
* Released under the MIT License.
*/
/**
* Save the file
*
* @private
* @param data - file data
* @param filename - the name of the file
*/
function saveFile(data, filename) {
var urlObject = window.URL || window.webkitURL || window;
var blob = new Blob([data]);
var link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
link.href = urlObject.createObjectURL(blob);
link.download = filename;
link.click();
}
/**
* Download secondary system documents
*
* @private
* @param url - link
* @param filename - the name of the file
*/
function downloadUrlFile(url, filename) {
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = function () {
if (xhr.status === 200) {
saveFile(xhr.response, filename);
}
};
xhr.send();
}
/**
* New tab to download files
*
* @private
* @param url - link
* @param filename - the name of the file
*/
function openFile(url, filename, fileType) {
var dom = document.createElement('a');
// if (['pdf', 'txt'].includes(fileType)) console.log('is pdf')
dom.style.display = 'none';
dom.download = filename;
dom.href = url;
document.body.appendChild(dom);
dom.click();
document.body.removeChild(dom);
}
/**
* Several ways of file downloading:
* 1. For file formats that some browsers do not recognize. Enter the file URL in the address bar, window.location.href = URL, window.open(URL);
* 2. using a tag download attribute (or js create a tag);
* 3. browser-recognizable pdf, txt files, back-end compatible with handling attachment;
* 4. add token in the header for authenticated download, use XmlHttpRequest to want to backend to launch the request
*
* @param url - link
* @param filename - filename
* @param type - download type 'href','open','download','request'
*/
function download(url, filename, type) {
var _a, _b;
if (type === void 0) {
type = 'download';
}
var name = ((_a = /[^\/]+$/.exec(url)) === null || _a === void 0 ? void 0 : _a[0]) || '';
(_b = /[^\.]+$/.exec(name)) === null || _b === void 0 ? void 0 : _b[0].toLowerCase();
if (type === 'open') {
window.open(url);
} else if (type === 'href') {
window.location.href = url;
} else if (type === 'request') {
downloadUrlFile(url, filename || name);
} else {
openFile(url, filename || name);
}
}
var index_default = {
version: '1.5.1',
download: download,
downloadUrlFile: downloadUrlFile,
openFile: openFile,
saveFile: saveFile
};
var version = '1.5.1';
export { index_default as default, download, downloadUrlFile, openFile, saveFile, version };