LoginSignup
5
1

More than 5 years have passed since last update.

JavascriptでラージファイルのMD5計算

Last updated at Posted at 2017-11-14

JavascriptでMD5計算する方法

webpackを使用していればビルトインのモジュールを使用することで、大体は事足ります。
こちらを参考にどうぞ。

が、5GBくらいのファイルをMD5計算したいと依頼された場合は対処しきれなくなります。
cryptoモジュールがエラーを起こしてくれます。
どうやら、メモリをどか食いする模様・・・

このライブラリを使用すれば解決できました。
npmも対応しているので便利。
以下を参考にどうぞ。

import md5 from 'js-md5';

/**
 * 入力されたファイルに対してMD5を計算して取得
 * @property {Object} file Fileオブジェクト
 */
getMd5(file) {
  const hash = md5.create();
  const chunkSize = 1000; // 一度に読み取るサイズを指定
  let offset = 0; // 読込開始位置
  let blockRead = null;

  // 分割されたファイルの読み込み関数
  const readContent = (evt) => {
    const result = new Uint8Array(evt.target.result);

    if (evt.target.error) {
      // エラー処理を記述・・・
    }

    offset += result.length;
    hash.update(result);

    if (offset >= file.size) {
      // 計算結果表示
      console.log(hash.hex());
    } else {
      blockRead(offset);
    }
  };
  // 再帰読込関数
  blockRead = (_offset) => {
    const blob = file.slice(_offset, chunkSize + _offset);
    const fileReader = new FileReader();
    fileReader.onloadend = readContent;
    fileReader.readAsArrayBuffer(blob);
  };

  // ファイル読み込み開始
  blockRead(offset);
}
5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1