<input type="file"> で選択したファイルのバイナリを16進数で表示するサンプル
バイナリエディタで見るような
<input type="file">
で選択したファイルを16進ダンプするサンプル。
選択したファイルは input
要素の files
属性でアクセスできる。files
は FileList
なので、ここから File
が取れる。
File
は Blob
の親戚なので、FileReader
で ArrayBuffer
→ Uint8Array
と変換することでバイトの配列にできる。このサンプルでは Uint8Array
を1要素ずつ16進数に変換して表示してる。
試しにGIFファイルを読み込ませてみると、最初の3バイトが 0x47 0x49 0x46
("GIF") になってるはず。
See the Pen dump-file-contents-in-hexadecimal by napoporitataso (@napoporitataso) on CodePen.
<!doctype html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<title>サンプル</title>
<style type="text/css">
.form {
margin: 7px 0;
}
#result {
max-width: 800px;
width: 100%;
min-height: 300px;
font-family: monospace;
}
</style>
</head>
<body>
<div class="form"><input type="file" id="file" /> <button type="button" id="button">バイナリ表示</button></div>
<textarea id="result"></textarea>
<script src="./script.js"></script>
</body>
</html>
document.getElementById('button').addEventListener('click', (event) => {
// 選択されたファイル取得
const elem = document.getElementById('file');
if (elem.files.length <= 0) {
alert('ファイルが選択されていません。');
return;
}
const file = elem.files[0];
// 大きさチェック
if (file.size > 51200) {
alert('50KB以下のファイルを指定してください。');
return;
}
// ファイル内容をバイト列に変換
const reader = new FileReader();
reader.addEventListener('load', (event) => {
const bytes = new Uint8Array(event.target.result);
// 1バイトずつ文字列にして連結
let hexstr = '';
bytes.forEach((value) => {
if (hexstr !== '') {
hexstr += ' ';
}
// 16進数に変換 → 大文字に変換 → 2桁でゼロパディング
hexstr += ('00' + value.toString(16).toUpperCase()).slice(-2);
});
// textareaに表示
document.getElementById('result').value = hexstr;
});
reader.readAsArrayBuffer(file);
});