标签归档:angularjs

javascript 计算文件md5

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://newpass.com/static/vendor/angular/angular.min.js"></script>
    <script src="//cdn.bootcss.com/jquery/3.1.1/jquery.js"></script>
    <script src="//cdn.rawgit.com/satazor/SparkMD5/master/spark-md5.min.js"></script>

</head>
<body>


<div ng-app="testapp" ng-controller="testctl">
    <input type="button" ng-click="two()" value="two">

<input id="file" type="file">
</div>

<script>
    (function () {
        'use strict';
        window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
        angular
                .module('testapp', [
                ])
                .controller('testctl',['$scope','$timeout','$http','$q',function ($scope,$timeout,$http,$q) {

                    $scope.two = function () {
                        var xx=$('#file').get(0).files[0];
                        $q.when($scope.md5(xx)).then(function (e) {
                            console.log(e);
                        });
                    };

                    $scope.md5 = function (file) {
                        var deferral_local = $q.defer();

                        var defer = $q.defer();
                        var promise = defer.promise;

                        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();

                        function loadNext() {
                            var fileReader = new FileReader();
                            fileReader.onload = function (e) {
                                spark.append(e.target.result); // append array buffer
                                currentChunk++;
                                if (currentChunk < chunks)
                                    loadNext();
                                else
                                    defer.resolve(spark.end());
                            };
                            var start = currentChunk * chunkSize,
                                    end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
                            fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
                        }

                        promise.then(loadNext())
                                .then(function (md5) {
                                    deferral_local.resolve( { status: md5 } );
                                });

                        return deferral_local.promise;
                    }
                }]);

    }());
</script>

</body>
</html>