/******************************************************************* Module : /assets/js/download.js Desc. : Fungsi-fungsi download data & laporan Created By : Siau Pheng (siaupheng@3fonia.com). Created Date : April 1st, 2011. Last Modified : November 2nd, 2026. (c) 3FONIA Software; WWW.3FONIA.COM. ******************************************************************* * * Class Download * * Download atau Share file. * * @license MIT, https://www.3fonia.com * @copyright Copyright (c) 2008-2026, Siau Pheng * * @param {object} options * @param {string} options.url - Endpoint URL File * @param {string} [options.filename='file.bin'] - Default file name for download is header is missing * @param {string} [options.title] - Title for share file * @param {string} [options.text] - Text for share file * @param {Array} [options.params] - Request payload */ class Download { constructor(options = {}) { this.url = typeof options === 'string' ? options : options.url || ''; this.filename = options.filename || 'file.bin'; this.title = options.title || ''; this.text = options.text || ''; this.params = options.params || []; } addParam(id, val) { this.params.push(val !== undefined ? `${id}=${encodeURIComponent(val)}` : id); return this; } async _exec(isShare = false) { if (!this.url) { console.warn('Url File Download dibutuhkan!'); return; } await $.ajax({ type: 'POST', url: this.url, data: FoniaJS.RequestParam(this.params), xhrFields: { responseType: 'blob' } }) .done((blob, status, xhr) => { let filename = this.filename; const disposition = xhr.getResponseHeader('Content-Disposition'); const match = disposition?.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/); if (match?.[1]) filename = match[1].replace(/['"]/g, ''); if (!isShare) { const url = URL.createObjectURL(blob); const link = Object.assign(document.createElement('a'), { href: url, download: filename }); link.click(); URL.revokeObjectURL(url); } else { const file = new File([blob], filename, { type: blob.type }); if (isShare && navigator.canShare?.({ files: [file] })) { navigator.share({ files: [file], title: this.title || filename, text: this.text }); } file = null; } }) .fail((xhr, status, err) => console.error('Gagal download File karena : ', err)); } share() { return this._exec(true); } download() { return this._exec(false); } }