1

From a browser, I would like to ask the server if a file that has been selected in a file input is identical to the one that it would replace on the server, if sent in a PUT request. I would use this comparison to decide whether or not to enable a save button.

To do that, I figure I should generate an ETag for the blob and then compare that with the ETag header returned by a HEAD request for that resource.

My question is, is there a browser API call that will return an ETag for a file-like object?

Rough idea:

<input type="file" onchange="function( event ) {
    console.log( ETagUnicorn.generate( event.target.files[0] ));
}" />
Dan Ross
  • 3,596
  • 4
  • 31
  • 60
  • You would need to know what hashing algorithm the server is using to calculate the ETag (S3 uses MD5 in most cases, for example) and then simply run that hashing routine on the client side. – Nate Barbettini Mar 08 '15 at 14:21
  • The browser and the server must already be using the same hashing algorithm for ETags to work at all. Can I ask the browser to run that algorithm on a blob of mine, or would I really have to find / write a Javascript implementation? I don't want to have to renegotiate the algorithm with the server, if the browser already has that figured out. – Dan Ross Mar 08 '15 at 14:24
  • I suppose if I control both ends, then I can just decide which algorithm to use. Then the only issue is that it would be better if the browser did this in native code than if I do it in JS. But I guess that's not a showstopper. – Dan Ross Mar 08 '15 at 14:30
  • 1
    And [this answer](https://stackoverflow.com/questions/24542959/how-does-a-etag-work-in-expressjs#answer-24627577) about ETags in ExpressJS shows how to select the algorithm on the server. On the client, I could use something like [bluimp-md5](https://www.npmjs.com/package/blueimp-md5). I'll turn this into an answer once I'm sure it works. – Dan Ross Mar 09 '15 at 06:35
  • That's what I would do. I'm not (currently) aware of a way to "tap into" the browser's native hashing implementation. Plus, by doing it yourself, you control the entire operation on both sides. (And from my understanding, some of the JavaScript MD5 hashing libraries are pretty fast.) – Nate Barbettini Mar 09 '15 at 15:27

0 Answers0