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