在浏览器中获取文件或字串的md5一个开源代码SparkMD5, 本文获取文件的md5就是用它来做
1. copy文件spark-md5.js到目录中:
下载开源代码包,解压后将里面的spark-md5.js copy到自己项目下 下载地址:1. http://download.csdn.net/detail/casun_li/9166469 2. https://github.com/satazor/SparkMD5
ps一:在meter的项目中就copy到client目录下,spark-md5.js在服务器端运行会报错
ps二:代码包中有示例代码,我们开发时可参照使用
2. 在js文件中的使用
var running = false;
getFileMd5=function(file,template){
if (running) {
return;
}
if (!file) {
return;
}
var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
chunkSize = 2097152, // 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++;
if (currentChunk < chunks) {
loadNext();
} else {
running = false;
var md5=spark.end();
template.find("#inputMd5sum").value = md5;
console.info('getFileMd5 finished loading computed hash',md5); // Compute hash
}
};
fileReader.onerror = function () {
running = false;
console.warn('oops, getFileMd5 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));
}
running = true;
loadNext();
}
//此处为在使用CollectinFS上传文件时的调用 其他调用场景请参照开源代码示例
Template.uploadupdatezip.events({
'change #update-zip': function(event, template) {
FS.Utility.eachFile(event, function(file) {
updatezipFileRecords.insert(file, function (err, fileObj) {
if (err) {
console.log('上传文件失败:'+err);
return;
}
getFileMd5(file,template);//此处就是调用获取md5的代码,此处传入 template是为了拿到md5后将之显示到界面
});
});
}
});
原文:http://blog.csdn.net/casun_li/article/details/49000683
参考文档:http://blog.csdn.net/a258831020/article/details/45867191