80 lines
2.8 KiB
JavaScript
80 lines
2.8 KiB
JavaScript
/**
|
|
* @description downloadボタンを押下したらCSVファイルをzip圧縮してダウンロードする
|
|
*/
|
|
|
|
|
|
// ダウンロードボタン
|
|
const downloadButton = document.getElementById('download-button');
|
|
const downloadButtonFile = document.getElementById('download-button-file');
|
|
|
|
// ダウンロードボタンを押下した時の処理を記載する
|
|
downloadButton.addEventListener('click', async () => {
|
|
// ダウンロードボタンを無効化する
|
|
downloadButton.disabled = true;
|
|
// ダウンロード処理を実行する
|
|
try {
|
|
const zip = new JSZip();
|
|
// ZIPにファイルを追加
|
|
zip.file("hello.txt", "Hello, this is a ZIP file!");
|
|
zip.file("world.txt", "Hello, this is a ZIP file!");
|
|
|
|
// ZIPを生成してダウンロード
|
|
const zipBlob = await zip.generateAsync({ type: "blob" });
|
|
const a = document.createElement("a");
|
|
a.href = URL.createObjectURL(zipBlob);
|
|
a.download = "example.zip";
|
|
document.body.appendChild(a);
|
|
a.click();
|
|
document.body.removeChild(a);
|
|
} catch (e) {
|
|
// エラーが発生した場合
|
|
console.error(e);
|
|
alert('ダウンロードに失敗しました');
|
|
} finally {
|
|
// ダウンロードボタンを有効化する
|
|
downloadButton.disabled = false;
|
|
}
|
|
});
|
|
|
|
|
|
downloadButtonFile.addEventListener('click', async () => {
|
|
// ダウンロードボタンを無効化する
|
|
downloadButtonFile.disabled = true;
|
|
try {
|
|
const files = [
|
|
{ name: "text1.csv", url: "assets/data/test_data_1.csv" },
|
|
{ name: "text2.csv", url: "assets/data/test_data_2.csv" }
|
|
];
|
|
|
|
const zip = new JSZip();
|
|
|
|
// CSV ファイルを取得して ZIP に追加
|
|
await Promise.all(
|
|
files.map(async (file) => {
|
|
const response = await fetch(file.url);
|
|
if (!response.ok) throw new Error(`Failed to fetch ${file.name}`);
|
|
const text = await response.text();
|
|
zip.file(file.name, text);
|
|
})
|
|
);
|
|
|
|
// ZIP を生成してダウンロード
|
|
zip.generateAsync({ type: "blob" }).then((blob) => {
|
|
const link = document.createElement("a");
|
|
link.href = URL.createObjectURL(blob);
|
|
link.download = "files.zip";
|
|
document.body.appendChild(link);
|
|
link.click();
|
|
document.body.removeChild(link);
|
|
}).catch(console.error)
|
|
} catch (e) {
|
|
// エラーが発生した場合
|
|
console.error(e);
|
|
alert('ダウンロードに失敗しました');
|
|
}
|
|
finally {
|
|
// ダウンロードボタンを有効化する
|
|
downloadButtonFile.disabled = false;
|
|
}
|
|
});
|