How to clear the contents of FileReader() buffer?

Hanley Soilsmith

I have a an HTML file uploader with an onChange function that finds the SHA256 hash of the file I have uploaded. My problem is that if I select a new file, it seems to be "building up" the contents of the buffer (thus returning the wrong hash of every file uploaded except the first one). Here is an example of what is happening. Each file is selected in order:

one.txt returns 6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b (correct)
two.txt returns 1e5e6cdb24208b723fa1631b107613cb1084c202a3b48fc6e3ddf9d458adf5ea
one.txt returns 2ebc9be2494f13b2ec93f578bea1002be847c7fad8a5bf27ddd674547121a284

I have tried to put the buffer into a state, and use the state to find the hash. The hope is that each time the DOM is reloaded (by calling the onChange() function), I would get a fresh buffer. Either I am doing it wrong, or it isn't working. Here is the full code, any thoughts?

import React, { Component } from "react";

const crypto = require("crypto");
const hash = crypto.createHash("sha256");

class SearchPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      hashOutput: "",
      files: null,
    };
  }

  onChange(e) {
    let files = e.target.files;
    let reader = new FileReader();
    this.setState({ fileName: files[0].name });
    this.setState({ files: files[0] }, () => {
      reader.readAsArrayBuffer(this.state.files);
    });
    console.log(this.state.files);

    reader.onload = e => {
      hash.update(Buffer.from(e.target.result));
      const hashOutput = hash.digest("hex");
      this.setState({ hashOutput });
      console.log(hashOutput);
    };
  }

  render() {
    return (
        <div onSubmit={this.onFormSubmit}>
          <input type="file" name="file" onChange={e => this.onChange(e)} />
        </div>
    );
  }
}
Per Digesen

Remove the const hash from the top and try something like this:

onChange(e, hash) {
let files = e.target.files;
let reader = new FileReader();
this.setState({ fileName: files[0].name });
this.setState({ files: files[0] }, () => {
  reader.readAsArrayBuffer(this.state.files);
});
console.log(this.state.files);

reader.onload = e => {
  hash.update(Buffer.from(e.target.result));
  const hashOutput = hash.digest("hex");
  this.setState({ hashOutput });
  console.log(hashOutput);
  };
}

render() {
return (
    <div onSubmit={this.onFormSubmit}>
      <input type="file" name="file" onChange={e => 
      this.onChange(e, 
      crypto.createHash("sha256"))} />
    </div>
    );
   }
  } 

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related