Compress the picture file on the Angularjs client and upload it

Source: Internet
Author: User

The main use of HTML5 canvas to compress the image, and then converted to Dataurl, and then dataurl into a blob file, BLOB objects can be directly assigned to Formdata.



App.service (' Util ', function ($q) {var datauritoblob = function (Datauri) {//convert base64/urlencoded Data Comp        Onent 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/he                        ight;                    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};});


Since currently angualrjs not support through multiform data upload files, so use the following code can upload files in 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);}        );}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Compress the picture file on the Angularjs client and upload it

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.