土曜日, 11月 08, 2025

Let's start JavaScript 86 
HTML上でファイル名を差し替え


HTML上で指定した2つのファイルのファイル名を指し変えます。HTML/JavaScript だけではローカルファイルを直接リネーム不可なので、変更後のファイルはダウンロードフォルダーにコピーします。

<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<title>ファイル名(拡張子を除く部分)
を入れ替えてダウンロード</title>
<meta name="viewport" content=
    "width=device-width,initial-scale=1" />
<style>
body {
font-family: system-ui, -apple-system,
            "Segoe UI", Roboto,
            "Hiragino Kaku Gothic ProN",
            "メイリオ", sans-serif;
padding:20px;
background: black;
color: white;
}
label {
display:block;
margin:10px 0 6px;
}
.files {
margin-bottom: 12px;
}
.btn {
margin-top: 12px;
padding: 4px 12px;
background: khaki;
}
#log {
margin-top: 12px;
white-space:pre-wrap;
color:white;
}
</style>
</head>
<body>
<h3>2つのファイルの拡張子を除く名前部分を
入れ替えてダウンロード</h3>

<div class="files">
<label>ファイルAを選択</label>
<input id="fileA" type="file" />
<div id="nameA"></div>
</div>

<div class="files">
<label>ファイルBを選択</label>
<input id="fileB" type="file" />
<div id="nameB"></div>
</div>

<button id="swapBtn" class="btn">
    ファイル名を入れ替えてダウンロード</button>

<div id="log"></div>

<script>
(function () {
const fileAInput = document.getElementById('fileA');
const fileBInput = document.getElementById('fileB');
const nameA = document.getElementById('nameA');
const nameB = document.getElementById('nameB');
const swapBtn = document.getElementById('swapBtn');
const log = document.getElementById('log');

function showFileName(el, file) {
if (!file) { el.textContent = ''; return; }
el.textContent = `${file.name} (${file.type ||
     'unknown'}, ${file.size} bytes)`;
}

fileAInput.addEventListener('change', () =>
    showFileName(nameA, fileAInput.files[0]));
fileBInput.addEventListener('change', () =>
    showFileName(nameB, fileBInput.files[0]));

function splitBaseAndExt(filename) {
const i = filename.lastIndexOf('.');
if (i <= 0) { // ドットがないか先頭にある場合は拡張子なし扱い
return { base: filename, ext: '' };
}
return { base: filename.slice(0, i), ext: filename.slice(i) };
    // extにドット含む
}

function downloadBlob(blob, filename) {
const a = document.createElement('a');
const url = URL.createObjectURL(blob);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(() => {
URL.revokeObjectURL(url);
document.body.removeChild(a);
}, 1000);
}

swapBtn.addEventListener('click', async () => {
log.textContent = '';
const fA = fileAInput.files[0];
const fB = fileBInput.files[0];

if (!fA || !fB) {
log.textContent = '両方のファイルを選択してください。';
return;
}

// 同一ファイル選択の防止(同じFileオブジェクトなら中身は同じ)
if (fA === fB) {
log.textContent =
'同じファイルが選ばれています。別々のファイルを選択してください。';
return;
}

// base / ext を分割
const sa = splitBaseAndExt(fA.name);
const sb = splitBaseAndExt(fB.name);

// 新しい名前:ベースを入れ替え、拡張子は元のファイルごとに保持
const newNameA = sb.base + sa.ext;
// fileAの拡張子はそのまま、baseはBのもの
const newNameB = sa.base + sb.ext;

log.textContent = `新しいダウンロード名:
\n- ファイルA → ${newNameA}
\n- ファイルB → ${newNameB}
\n\nダウンロードが開始されます。
(ブラウザにより自動ダウンロードがブロックされる場合があります)`;

try {
// ファイルの内容をそのまま Blob としてダウンロード
// (MIMEタイプは元の file.type を使用)
// ここでは File をそのまま使えるので blob化は不要だが
// download のためにそのまま使う
// いったん arrayBuffer を取って Blob を生成しても可。
// ここでは直接 File を渡す。
downloadBlob(fA, newNameA);
// 少し遅らせて2つ目をダウンロード
// (同時クリックでブロックされるブラウザがあるため)
setTimeout(() => downloadBlob(fB, newNameB), 200);
} catch (err) {
log.textContent += '\nエラー: ' + err;
}
});
})();
</script>
</body>
</html>

実行したら、処理したいファイルを選択します。

次に[ファイル名を入れ替えてダウンロード]をクリックすれば・・・

[許可]をクリックすれば、ダウンロードに変更後のコピーを保存します。


元データ
差し替え後