javascript 计算文件MD5 浏览器 javascript读取文件内容
原则上说,浏览器是一个不安全的环境。早期浏览器的内容是静态的,用户上网冲浪,一般就是拉取网页查看。后来,随着互联网的发展,浏览器提供了非常丰富的用户交互功能。从早期的表单交互,到现在的websocket实时通信,乃至html5的流行。
html5给前段开发带来了许多有力的工具,以前浏览器大多通过flash插件进行文件的上传和下载,现在我们可以利用html5给我们带来的fileReader api,读取用户通过表单选中的文件内容。
fileReader详情请移步:
https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader
javascript 计算文件MD5值,请移步:
https://github.com/satazor/js-spark-md5
demo实现:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <form id="fileupload" action="" method="POST" enctype="multipart/form-data"> <div> <div> 添加文件 <input type="file" name="" id="fileinput"> </div> <progress class='progressbar' value="0" max="100" style='width:500px;margin-top:20px'></progress> <div style='margin-top:20px'> <span id="handler_info" ></span> </div> </div> </form> <script src="./spark-md5.js" type="text/javascript"></script> <script> function get_filemd5sum(ofile) { var file = ofile; var tmp_md5; var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice, // file = this.files[0], chunkSize = 8097152, // Read in chunks of 2MB chunks = Math.ceil(file.size / chunkSize), currentChunk = 0, spark = new SparkMD5.ArrayBuffer(), fileReader = new FileReader(); fileReader.onload = function(e) { // console.log('read chunk nr', currentChunk + 1, 'of', chunks); spark.append(e.target.result); // Append array buffer currentChunk++; var md5_progress = Math.floor((currentChunk / chunks) * 100); console.log(file.name + " 正在处理,请稍等," + "已完成" + md5_progress + "%"); var handler_info = document.getElementById("handler_info"); var progressbar = document.getElementsByClassName("progressbar")[0]; handler_info.innerHTML=file.name + " 正在处理,请稍等," + "已完成" + md5_progress + "%" progressbar.value =md5_progress; if (currentChunk < chunks) { loadNext(); } else { tmp_md5 = spark.end(); console.log(tmp_md5) handler_info.innerHTML = file.name + "的MD5值是:" + tmp_md5; } }; fileReader.onerror = function() { console.warn('oops, something went wrong.'); }; function loadNext() { var start = currentChunk * chunkSize, end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize; fileReader.readAsArrayBuffer(blobSlice.call(file, start, end)); } loadNext(); } var uploadfile = document.getElementById('fileinput') uploadfile.onchange = function(e){ var file = this.files[0]; if(!file) { alert('请选择文件!'); return false; } get_filemd5sum(file) } </script> </body> </html>
结果:
完成效果: