LoginSignup
9
7

More than 5 years have passed since last update.

[JS]ファイルを読み込んでハッシュ化しよう

Last updated at Posted at 2019-02-04

:pencil2:前書き:writing_hand_tone5:

ローカルのファイルを読み込んでそれをハッシュ化するという機能を実装する機会があったの方法をまとめておきます

ブロックチェーンのハッカソンとかで使う機会があるかもしれないです

:relaxed:create-react-app:frowning2:

$ npx create-react-app hash
$ cd hash
$ npm start

:fist:js-md5:raised_hand_tone5:

今回はMD5というハッシュ関数を使ってファイルをハッシュ化します
js-md5という簡単にハッシュ化できるライブラリがあったのでそれを使います
js-md5へのリンク

$ npm install --save js-md5

:airplane:実装例:airplane:

App.jsを書き換えましょう

App.js
import React, { Component } from "react";
import md5 from 'js-md5';

class App extends Component {
  constructor(props) {
    super(props);
  this.state = {
    hash: null
  }
}

 getMd5 = () => {
   const element = document.getElementById('file');

   //ファイルが選択されたか
   if(!(element.value)) return;

   //FileReaderクラスに対応しているか
   if (!(window.FileReader)) return;

   //0番目のファイルオブジェクトを取得
   const file = element.files[0];

   //FileReaderオブジェクトを生成
   const fileReader = new FileReader();

   //読み込み時に実行されるイベント
   fileReader.onload = function () {
     const res = fileReader.result;
     //MD5ハッシュ関数でハッシュ化
     const hash = md5(res);
     this.setState({hash})
   }.bind(this); //関数をbindしないとhashをsetStateできない

   //読み込みを開始する(ArrayBufferオブジェクトを得る)
   fileReader.readAsArrayBuffer(file);
 }

 render() {
   return (
     <div className="App" align="center">
       <input type='file' id='file' onChange={this.getMd5}></input>
       <p>{this.state.hash}</p>
     </div>
   );
 }
}
export default App;

:sunny:結果:snowman2:

スクリーンショット 2019-02-04 16.53.38.png

こんな感じでファイルのハッシュ値が表示されます
楽しいですね!!

9
7
1

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
9
7