Skip to content

Instantly share code, notes, and snippets.

@fernandoc1
Created October 27, 2014 12:09
Show Gist options
  • Save fernandoc1/79ee1d0721c399519fa5 to your computer and use it in GitHub Desktop.
Save fernandoc1/79ee1d0721c399519fa5 to your computer and use it in GitHub Desktop.
Upload files with SHA1 hash calculation in client side.
<html>
<head>
<script type="text/javascript">
output = null;
function initApplication()
{
output = document.getElementById("outputPre");
}
function sendRequest()
{
filesInput = document.getElementById("filesInput");
senderWorker = new Worker("upload_files.js");
senderWorker.postMessage(filesInput.files);
senderWorker.onmessage = function(e)
{
output.innerHTML = e.data;
}
}
</script>
</head>
<body onload="initApplication()">
<input type="file" name="files[]" id="filesInput" multiple="" directory="" webkitdirectory="" mozdirectory="">
<button onclick= "sendRequest()">Send</button>
<pre id="outputPre"></pre>
</body>
</html>
#! /usr/bin/env python
import os
import sys
import cgi
import tempfile
import hashlib
print "Content-type: text/html\n\n"
form = cgi.FieldStorage()
data = form['file'].file.read()
m = hashlib.sha1()
m.update(data)
filename = m.hexdigest()
path = '/tmp/FILES/'+str(filename)
f = open(path, "w")
f.write(data)
f.close()
importScripts("rusha.js");
self.addEventListener('message', function(e)
{
var files = e.data;
console.log(new Date());
for (i = 0; i < files.length; i++)
{
postMessage(files[i].webkitRelativePath);
var reader = new FileReaderSync();
var content = reader.readAsArrayBuffer(files[i]);
var hash = (new Rusha()).digestFromBuffer(content);
console.log(files[i].webkitRelativePath+" "+hash);
var formData = new FormData();
formData.append("file", files[i]);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//postMessage(files[i].webkitRelativePath);
}
}
xmlhttp.open("POST", "upload.py", false);
xmlhttp.send(formData);
}
console.log(new Date());
postMessage("DONE");
}, false);
@duhaime
Copy link

duhaime commented Dec 26, 2022

This sha1 calculation is not clientside...

@omranjamal
Copy link

@duhaime yes it is. rusha.js is a pure javascript implementation of SHA1.

@duhaime
Copy link

duhaime commented Jul 18, 2023

I mean the client runs a hash that says where the file will be stored, but we're not uploading the hash, we're just logging it on the client

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment