您的位置:首页 > Web前端 > JavaScript

Meter 上传文件前,js计算文件的md5值

2015-10-09 15:42 531 查看
在浏览器中获取文件或字串的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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: