forked from izu/student-web-if-development-kit
27 lines
938 B
JavaScript
27 lines
938 B
JavaScript
export class FileDownloader {
|
|
static async download(url, filename) {
|
|
try {
|
|
const response = await fetch(url);
|
|
if (!response.ok) throw new Error('Gagal mengunduh berkas.');
|
|
const blob = await response.blob();
|
|
const blobUrl = URL.createObjectURL(blob);
|
|
this._click(blobUrl, filename);
|
|
URL.revokeObjectURL(blobUrl);
|
|
} catch (err) {
|
|
console.warn('Unduh via Blob gagal, beralih ke parameter Directus:', err);
|
|
const fallbackUrl = url.includes('?') ? `${url}&download` : `${url}?download`;
|
|
this._click(fallbackUrl, filename);
|
|
}
|
|
}
|
|
|
|
static _click(href, filename) {
|
|
const a = document.createElement('a');
|
|
a.style.display = 'none';
|
|
a.href = href;
|
|
a.download = filename;
|
|
document.body.appendChild(a);
|
|
a.click();
|
|
document.body.removeChild(a);
|
|
}
|
|
}
|