0

I'd like to compare the hashed version of the file against the data stored in the database, so I can abort duplicate uploads.

Being quite "new" to the subjects of hashing and the FileReader API, I'm finding the process a bit confusing. I am using the frontend library SparkMD5.js

Test n1 compare two strings:

// frontend
$.post(url, {sparkMD5('random text')})

// backend
$input->hash == md5('random text')  // outputs true

Test n2 - inside fineuploader onSubmit event handler

// frontend
var file = this.getFile(id);
var reader = new FileReader();
//
reader.onload = function(e) {
  var data = reader.result;
  var hexHash = SparkMD5.hash(data);
  console.log(hexHash);
}

var res = reader.readAsDataURL(file); // or reader.readAsBinaryString(file)

......

//backend
$file = Input::file('qqfile');
$hash = md5(file ) // or md5_file(file )
$hash == $input->hexHash // outputs false

My questions:

1) Why is the result of md5($file) == md5_file($file) \\ false ?

2) What's the correct way of reading a file readAsDataURL or readAsBinaryString ?

3) Is there a way to read and hash the result of fineuploader's getFile(id) which returns File or Blob, without using filereader api?

Answers to the above questions may be considered broad and out of scope of my immediate problem, but i'd like to understand the subject as best as possible.

Thanks.

Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167
Enrico
  • 408
  • 6
  • 13

2 Answers2

2
  1. Input::file() returns an instance of Illuminate\Http\UplaodedFile, so to get the hash of its contents you can do the following:
// md5_file takes in the file path as argument
$hash = md5_file(Input::file('yourfile')->path());
  1. readAsDataURL() is much safer because the file is encoded as base64. Just make sure that the server is aware of the encoding, meaning remove the first characters up to the comma then decode the rest as base64. More information here: fileReader.readAsBinaryString to upload files

  2. According to this you still have to use filereader: How to include Content-MD5 header in FineUploader Azure request?.

aljo f
  • 2,430
  • 20
  • 22
0

Thanks to @alio f I was able to come up with a solution. Here's the code.

frontend

var t = this;

var reader = new FileReader();
var file = this.getFile(id);
reader.addEventListener("load", function () {
  var base64result = reader.result.split(',')[1]; // only get base64 string
  var hash = SparkMD5.hash(base64result);
}, false);

var data = reader.readAsDataURL(file);

Refer to FineUploader docs for the onSubmit handler.

backend

$this->file = Input::file('qqfile');
$base64 = base64_encode(file_get_contents($this->file));
$hash = md5($base64);

Comparing frontend's md5 and backend's md5 now returns true

Enrico
  • 408
  • 6
  • 13