This repository has been archived by the owner on May 10, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
angular-file-md5.js
111 lines (85 loc) · 2.54 KB
/
angular-file-md5.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['angular', 'spark-md5'], factory);
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require('angular'), require('spark-md5'));
} else {
// Browser globals (root is window)
return factory(root.angular, root.SparkMD5);
}
}(this, function (angular, sparkMd5) {
'use strict';
var moduleName = 'ljungmann.fileMd5';
angular.module(moduleName, [])
.provider('fileMd5Service', [function() {
var settings = {
chunkSize: 2097152 // 2 MB
};
this.configure = function(additionalSettings) {
angular.extend(settings, additionalSettings);
return this;
};
this.$get = ['$q', function($q) {
return {
md5: function(file) {
var slicer = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
var currentChunk = 0;
var chunks = Math.ceil(file.size / settings.chunkSize);
var spark = new sparkMd5.ArrayBuffer();
var deferred = $q.defer();
var promise = deferred.promise;
var onLoadFn = function(event) {
spark.append(event.target.result);
deferred.notify({
loaded: currentChunk * settings.chunkSize + event.loaded,
total: file.size
});
currentChunk++;
if (currentChunk < chunks) {
loadData();
} else {
var md5sum = spark.end();
deferred.resolve(md5sum);
}
};
var onErrorFn = function (error) {
deferred.reject(error);
};
var loadData = function() {
var fileReader = new FileReader();
fileReader.onload = onLoadFn;
fileReader.onerror = onErrorFn;
var start = currentChunk * settings.chunkSize;
var end = ((start + settings.chunkSize) >= file.size) ? file.size : start + settings.chunkSize;
fileReader.readAsArrayBuffer(slicer.call(file, start, end));
};
promise.success = function(fn) {
promise.then(function(md5sum) {
fn(md5sum);
});
return promise;
};
promise.error = function(fn) {
promise.then(null, function(error) {
fn(error);
});
return promise;
};
promise.progress = function(fn) {
promise.then(null, null, function(stats) {
fn(stats);
});
return promise;
};
loadData();
return promise;
}
};
}];
}]);
return moduleName;
}));