码迷,mamicode.com
首页 > Web开发 > 详细

在angularjs客户端压缩图片文件然后上传

时间:2015-07-03 19:17:32      阅读:378      评论:0      收藏:0      [点我收藏+]

标签:angularjs   图片   压缩   base64   canvas   

主要是利用html5的canvas来进行图片的压缩,然后转化为dataURL,再有dataURL转化为Blob文件,Blob对象可以直接赋值给Formdata.



app.service('Util', function($q) {
   var dataURItoBlob = function(dataURI) {
        // convert base64/URLEncoded data component to raw binary data held in a string
        var byteString;
        if (dataURI.split(',')[0].indexOf('base64') >= 0)
            byteString = atob(dataURI.split(',')[1]);
        else
            byteString = unescape(dataURI.split(',')[1]);

        // separate out the mime component
        var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

        // write the bytes of the string to a typed array
        var ia = new Uint8Array(byteString.length);
        for (var i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }

        return new Blob([ia], {
            type: mimeString
        });
    };

    var resizeFile = function(file) {
        var deferred = $q.defer();
        var img = document.createElement("img");
        try {
            var reader = new FileReader();
            reader.onload = function(e) {
                img.src = e.target.result;

                //resize the image using canvas
                var canvas = document.createElement("canvas");
                var ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0);
                var MAX_WIDTH = 800;
                var MAX_HEIGHT = 800;
                var width = img.width;
                var height = img.height;
                if (width > height) {
                    if (width > MAX_WIDTH) {
                        height *= MAX_WIDTH / width;
                        width = MAX_WIDTH;
                    }
                } else {
                    if (height > MAX_HEIGHT) {
                        width *= MAX_HEIGHT / height;
                        height = MAX_HEIGHT;
                    }
                }
                canvas.width = width;
                canvas.height = height;
                var ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0, width, height);

                //change the dataUrl to blob data for uploading to server
                var dataURL = canvas.toDataURL('image/jpeg');
                var blob = dataURItoBlob(dataURL);

                deferred.resolve(blob);
            };
            reader.readAsDataURL(file);
        } catch (e) {
            deferred.resolve(e);
        }
        return deferred.promise;

    };
    return {
        resizeFile: resizeFile
    };

});


由于目前angualrjs暂不支持通过multiform data上传文件,所以利用如下的代码可以上传formdata里的文件

app.controller('CompanyCtrl', function($http, Util) {

        Util.resizeFile(input.files[0]).then(function(blob_data) {
            var fd = new FormData();
            fd.append("imageFile", blob_data);
            $http.post('http://your.domain.com/upload', fd, {
                headers: {'Content-Type': undefined },
                transformRequest: angular.identity
            })
                .success(function(data) {
                    $scope.model.company_pict = data[0];
                })
                .error(function() {
                    console.log("uploaded error...")
                });
        }, function(err_reason) {
            console.log(err_reason);
        });


}


版权声明:本文为博主原创文章,未经博主允许不得转载。

在angularjs客户端压缩图片文件然后上传

标签:angularjs   图片   压缩   base64   canvas   

原文地址:http://blog.csdn.net/alexwang1983/article/details/46744207

(1)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!