Thursday 15 March 2012

javascript - Converting base64 to Blob and Blob to base64 using FileReader in PhantomJS -



javascript - Converting base64 to Blob and Blob to base64 using FileReader in PhantomJS -

i have angular controller, should work images. have watcher property file in scope. if property contain array of files, these files (only first file) should read filereader , converted base64 string , added page. this:

$scope.$watch('file', function (files) { if (files && files.length > 0) { if (files[0].type && files[0].type.match('image.*')) { var reader = new filereader(); reader.onload = function (e) { render(e.target.result); }; reader.readasdataurl(files[0]); } } });

and render function:

function render (src) { var image = new image(); image.addeventlistener('load', function () { if (image.width < min_size || image.height < min_size) { $scope.error = $filter('localize')('uploaderwindow_imagesizeerror'); $scope.$apply(); } else { new global.icropper('original-image', { gap: 0, keepsquare: true, image: src, preview: ['cropped-image'] }); } }); image.addeventlistener('error', function () { $scope.error = $filter('localize')('uploaderwindow_selectimage'); $scope.$apply(); }); image.src = src; };

icropper should create img element in dom base64 in src attribute. problem is, have unit test functionality. test case:

it('should render new image file input', function () { var imagedata = image.split(',')[1], imagetype = image.split(',')[0].replace('data:', '').replace(';base64', ''), file = base64toblob(imagedata, imagetype); expect(originalimage.lastelementchild).tobe(null); runs(function () { $scope.file = [file]; $scope.$apply(); }); waitsfor(function () { homecoming originalimage.lastelementchild; }, 'waiting_original_form'); runs(function () { expect(originalimage.lastelementchild.src).tobe(image); }); });

variable image contains valid base64 string, originalimage.lastelementchild - img element, should created icropper. body of base64toblob function:

function base64toblob (b64data, contenttype) { var binary = atob(b64data.replace(/\s/g, '')), binarylength = binary.length, buffer = new arraybuffer(binarylength), view = new uint8array(buffer); (var = 0; < binarylength; i++) { view[i] = binary.charcodeat(i); } homecoming new blob([view], {type: contenttype}); }

this test passed in chrome, not in phantomjs:

timeout: timed out after 5000 msec waiting waiting_original_form

i think, it's because load event image not fired, error fired instead. don't understand why? know, blob not defined in phantomjs, utilize polyfill: https://github.com/eligrey/blob.js

javascript blob phantomjs karma-runner filereader

No comments:

Post a Comment