js获取文件md5库
在做文件系统时,上传下载需要获取到文件的md5。
上传获取文件md5优点:将文件md5传至后段服务器,若服务器已存在该文件,则将该文件关联,实现‘秒传’的功能。
下载获取文件md5优点:下载文件完成后将文件md5传给后端,后端判断文件下载是否完整。
##js-spark-md5类库实现快速获取文件md5
demo如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <form method="POST" enctype="multipart/form-data" onsubmit="return false;" > <input id=file type=file placeholder="select a file" /> </form> <pre id=log></pre> <script src="//cdn.rawgit.com/satazor/SparkMD5/master/spark-md5.min.js"></script> <script> var log=document.getElementById("log"); document.getElementById("file").addEventListener("change", function() { var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice, file = this.files[0], chunkSize = 2097152, // read in chunks of 2MB chunks = Math.ceil(file.size / chunkSize), currentChunk = 0, spark = new SparkMD5.ArrayBuffer(), frOnload = function(e){ // log.innerHTML+="\nread chunk number "+parseInt(currentChunk+1)+" of "+chunks; spark.append(e.target.result); // append array buffer currentChunk++; if (currentChunk < chunks) loadNext(); else log.innerHTML+="\n加载结束,文件md5:\n"+spark.end(); }, frOnerror = function () { log.innerHTML+="err"; }; function loadNext() { var fileReader = new FileReader(); fileReader.onload = frOnload; fileReader.onerror = frOnerror; var start = currentChunk * chunkSize, end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize; fileReader.readAsArrayBuffer(blobSlice.call(file, start, end)); }; loadNext(); }); </script> </body> </html>
js库在我百度网盘
链接: https://pan.baidu.com/s/1jIaJZrK 密码: yfbp