Menu
  • HOME
  • TAGS

Is it possible to send base64 image to an amazon s3 bucket via ngFileUpload post?

Tag: angularjs,canvas,amazon-s3,upload,ng-file-upload

I have a working script that when the file input changes, pick the files, sign their upload data in my django backend, and upload it from the frontend directly to my s3 bucket. It's working great. I'm using ng-file-upload to do it.

var doSignUrl = function(image, success, error){
    $http({
        url: scope.signUrl,
        params: {
            s3_object_name: image.name,
            s3_object_type: image.type
        },
        method: 'get'
    }).success(success).error(error);
};

var getUploadConfig = function(image, data){
    return {
        url: data.url,
        method: 'POST',
        fields : {
            key: data.path,
            AWSAccessKeyId: data.aws_access_key_id, 
            acl: data.acl,
            policy: data.policy, 
            signature: data.signature, 
            "Content-Type": image.type != '' ? image.type : 'application/octet-stream',
            filename: data.file_name
        },
        file: image,
    };
};

var doUpload = function(image){
    doSignUrl(image, function(signData){
        Upload.upload(getUploadConfig(image, signData)).progress(function(e){
            doProgress(image, parseInt(100.0 * e.loaded / e.total))
        }).success(function(data, status, header, config){
            doSuccess(image, signData.url+'/'+signData.path);
        }).error(function(data, status, header, config){
            doError(image);
        });
    }, function(data, status, header, config){
        console.log(status);
        console.log(data);
    });
}

for each file the file picker selects i call doUpload(file)

But my real objective is to crop the image in frontend using canvas before to upload. The problem is that when you crop image using canvas, the result is a base64 encoded image, not a file. So my final question is: is it Possible to upload this base64 image directly to s3?

Best How To :

With a lot of research i found out that you can send a blob instead of a file unsing ngFileUpload to s3.

I used this library to convert my base64 to a blob, and then passed the generated blob instead of the file in the Upload.upload() file parameter.

recursive function with an array as input

javascript,angularjs

Modify your function to this, function getChest(arr){ var pointer = 0; //random array pointer pointer = Math.round(Math.random() * (chest.length - 1)); //check for duplicate for(var i = 0; i < arr.length; i++){ if(arr[i].name === chest[pointer].name){ return getChest(arr); } } return chest[pointer]; }; Basically, the loop is breaking before the value...

Angularjs $watchCollection on $rootScope not triggered when values updated from directive

javascript,angularjs,events,angularjs-directive,angularjs-watch

Your actual problem is you are update $rootScope from the event which is outside the angular context, so its obivious that angular binding will not update because digest cycle doesn't get fired in that case. You need to fire it manually by using $apply() method of $rootScope el.bind('click', function(evt) {...

Can't save json data to variable (or cache) with angularjs $http.get

json,angularjs,web-services,rest

$http.get is asynchronous. When cache.get or return result are executed, HTTP request has not completed yet. How are you going to use that data? Display in UI? E.g. try the following: // Some View <div>{{myData}}</div> // Controller app.controller('MyController', function ($scope) { $http.get('yoururl').success(function (data) { $scope.myData = data; }); }); You...

navbar disappears but no dropdown

angularjs,bootstrap

This is built into bootstrap already. Viewing the html for bootstrap.com I see their button looks like this: <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#bs-navbar" aria-controls="bs-navbar" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> with the button they have data-target="#bs-navbar". "#bs-navbar" refers to...

AngularJS - binding/linking two directives together

javascript,angularjs,angularjs-directive

The key issue revolves around your use of isolated scopes: scope: { selectedId: '=' }, With controllerAs binding: controllerAs: 'vm', What this essentially does, to put it basically, is it places the view model onto the directives scope, accessed through the alias you assign in the controllerAs. So basically in...

$http.get returns actual php script instead of running it (yeoman, grunt)

php,angularjs,pdo,gruntjs

Change $http.get('/scripts/php/articles.php') to $http.get('http://YOURDOMAIN.COM/scripts/php/articles.php') Off course you need to replace YOURDOMAIN.COM with localhost or any other domain you are using....

AngularJS & Bootstrap Modal - loading template outside controller

angularjs,twitter-bootstrap,angular-bootstrap

A good way to reuse your template is to put it in a separate html file and put its url in templateUrl. So $modal can get it from server every time needed.

Using ng-click to toggle between two functions

javascript,angularjs,angular-ui,angular-ui-bootstrap

You can create a toggle() function which will call the function you want based on a variable tracking the state. You can then simply use this function in your template as ng-click="toggle()". Something like this. var toggled = false; $scope.toggle = function() { if (toggled) { $scope.clear(); } else {...

Uncommon “10 $digest iterations reached” case

angularjs

To answer your question directly, you can change the number of digest cycles as follows: app.config(function($rootScopeProvider){ $rootScopeProvider.digestTtl(20); }); But, I am cautious to recommend this as a general approach since, in all likelihood, the problem lies elsewhere your code (which is not specified in the question) and it just manifests...

remove char from string with angular

javascript,angularjs

Just use replace: If v_value is a string: value: {{item.v_value.replace('.', '')}} If v_value is a number, "cast" it to a string first: value: {{(item.v_value + '').replace('.', '')}} Basically, you can use JavaScript in those brackets....

Angular $http and Fusion Tables in IE9

javascript,angularjs,internet-explorer-9,google-fusion-tables

You should use the Angular $http.jsonp() request rather than $http.get(). JSONP or “JSON with padding” is the communication technique which allows for data to be requested from a server under a different domain (also known as a Cross Origin Request). Which is what you have used in your jQuery AJAX...

Redraw text over clearRect HTML5 Canvas

jquery,html5,canvas

One possible solution is that you move all your clearRect()'s out from the else-statements to the top and clear it from the start. Then you add text in a second step. That way you can also group the if-statements together to form a if-else if relationship (crappy explanation, just look...

How can this be undefined in the constructor of an Angular config class?

angularjs,constructor,typescript,undefined,this

Config functions aren't classes and shouldn't be written as such. Angular is invoking them without new and thus this will be undefined (or, God help you, window in non-strict mode). It doesn't really make sense to use a class here as there's no instance to be kept around. If you...

How do I add a class on ng-click from layout?

angularjs

In your plnkr the css for active-link was missing, and I wrapped the assigning of the clicked link in a function. Check this updated plnkr. The function is pretty basic: $scope.changeActiveLink = function(link) { $scope.activeLink = link; } Now the links are green when clicked. This is what you wanted...

Merge and sum values and put them in an array

javascript,arrays,angularjs,foreach

You cannot store key-value pair in array. Use object to store key-value pair. See comments inline in the code. var obj = {}; // Initialize the object angular.forEach(data, function(value, key) { if (value.start_date > firstdayOfWeek && value.start_date < lastdayOfWeek) { if (obj[value.firstname]) { // If already exists obj[value.firstname] += value.distance;...

REST API with token based authentication

angularjs,codeigniter,api,rest,token

You can use an API key, however - as you wrote - it's pure protection and easily accessible value - potential abuser just needs to view the source or investigate the queries. In general REST APIs are secured with tokens. At the beginning of the session (not in traditional meaning...

success and error function in the controller for a service

javascript,angularjs,angularjs-service,angularjs-http,angularjs-promise

..I want to write the success and error function of $http.get in the controller.. Usually, the .then() function takes two function arguments with first one as the success handler and seconf one as error handler. $http.get(url,options).then(function (response){ //success handler function },function(error){ //error handler function }) Alternatively, you can specify...

Can't get angular.js to loop through array and post to html

angularjs,ng-repeat

It looks like you have some syntax errors: var app = angular.module('myStore', []); app.controller('StoreController', function(){ this.products = [ { name: 'keyboard', price: 20.47, description: "well made from scratch", reviews: [ { stars: 5, body: "great fantadtic worksmanship", author: "[email protected]" }, { stars: 4, body: "amazing sale for the best", author:...

UI-Router : Prevent access to parent state

angularjs,angular-ui-router,state

There is a working example Make your state abstract: .state('app', { url: '/app', abstract: true, // here template: ' <div ui-view></div>', authenticate: true }) And add some default redirections: $urlRouterProvider.when('/app', '/app/state1'); $urlRouterProvider.otherwise('/app/state1'); The first 2 links below will redirect to 'app.state1' <a href="#/app"> // will be redirected to state1 <a...

How to define style to layout-margin flex variants, using Angular Material

css,angularjs,angular-material

Angular material doesn't add or remove the attributes based on the browser size, so both [flex] and [flex-sm] will always be on your element. That is why they both apply, you will have to write a media query with the same break point as angular material if you want to...

angular.js - simplest way to handle click inside controller

javascript,jquery,html,angularjs

You don't really want to handle any DOM stuff in controllers (a controller just ties data to the view, which happens to be the DOM). You want to use a directive for DOM manipulation. (However, yes, ng-click is a built-in directive that can run methods inside the controller). If you'd...

validation of AngularJS direcrives

angularjs,html5,html-validation

data- prefix can be used by any directive and the underlying directive name normalization process takes care of matching the directive attribute declaration with the directive implementation. More details about the normalization process is available in the directive user guide under section "Matching Directives". Hence adding data- prefix to to...

Create angular page in Django to consume data from JSON

angularjs,django,django-templates

You can add the angular app as a simple template view in Django views.py def index(request): return render(request, 'yourhtml.html', {}) urls.py .... url(r'^your_url/$', views.index), .... Then the index.html file can have your angular code...

How to use a service with Http request in Angular JS

javascript,angularjs

ofcservices.getnews() is a promise You need manage with the function sucess and error ofcservices.getnews(). success(function(data) { $scope.news=data }). error(function(data, status, headers, config) { //show a error }); As weel change app.factory('news' to app.factory('newsFactory' and call it in controller('news', function($scope, newsFactory) { You can get more data about promise in the...

AngularJS line break at points after a maximum length was reached

javascript,angularjs

Write a custom filter: angular.module('filters', []).filter('lineBreaker', function() { return function(input, breakLength) { var newString = ""; for (var i = 0; i < input.length; i++) { newString = newString+input[i]; if (i%breakLength == 0) { newString = newString+"\n"; } } return newString; }; }); Called like: {{ expression | lineBreaker: 10...

Angular controller error: 'Controller is not a function, got undefined'

javascript,angularjs,angularjs-controller

controller() is itself a function to be called, not a property to be assigned as you're doing. Try this instead: var app = angular.module('TourneyTime', ['ionic']); app.controller('HomeController', function($scope) { $scope.players = "testing"; }); ...

calling one controller from another controller

angularjs

You can normally use the controller in the modal open function but the controller2 must be in same module that controller1 belongs: angular.module('myModule').controller('controller1', ['$scope', myModuleController1]); angular.module('myModule').controller('controller2', ['$scope', myModuleController2]); or else you have to make your dependencies right in your app.js file if your controllers belong to separate modules myModule1, myModule2:...

Aligning StackPanel to top-center in Canvas

c#,wpf,xaml,canvas

If you don't want any input or hit testing on a certain element you should set the IsHitTestVisible property to false: <Grid> <Canvas Name="Canvas" Background="#EFECCA"> <DockPanel VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Width="{Binding ActualWidth, ElementName=Canvas}" Height="{Binding ActualHeight, ElementName=Canvas}" MouseLeftButtonDown="DockPanel_MouseLeftButtonDown" TouchDown="DockPanel_TouchDown" Panel.ZIndex="2" Background="Transparent"> </DockPanel> <Button Width="50" Height="50"...

How to add class on ng-click?

angularjs

If your using classes like active-link, x-y which have dash (-) then you have to wrap it in ' as below. ng-class="{'active-link' : activeLink==='PersonalInfo'}" if your classes like activeLink which are doesn't have dash (-) then you can avoid from ' but not a must. ng-class="{activeLink : activeLink==='PersonalInfo'}" here is...

Socket.IO message doesn't update Angular variable

javascript,angularjs,node.js,sockets

You need to wrap the change of the model (changing properties on the $scope), with $scope.$apply(function() {}) in order to to update the view. var container = angular.module("AdminApp", []); container.controller("StatsController", function($scope) { var socket = io.connect(); socket.on('message', function (msg) { console.log(msg); $scope.$apply(function() { $scope.frontEnd = msg; }); }); }); $apply()...

How to select multiple selected value from select option

angularjs,model-view-controller,ionic-framework,ionic

Here is the jsfiddle I used ng-repeat to build the select and ng-options to fill them, you then have to use the relative ng-model to get the selections. HTML: <div ng-app ng-controller="MyCtrl"> <select class="select fancy" ng-repeat="(i, item) in items" ng-model="searchOption[i]" ng-options="type.name for type in item.types"></select> <button ng-click="submitIt()">Submit</button> </div> Javascript: function...

Iframe does not show scrollbar

html,css,angularjs,iframe,ionic

You have hidden scrollbars in ionic.app.css: ::-webkit-scrollbar { display: none; } I don't know if it is possible to override this style so probably you have to remove it. Similar question....

AngularJS: Adding ng-click within element.append

angularjs,directive

You should compile the html to bind the directives like ng-click to scope properties. Other vice angular directives will not bind to the scope properties. var strElm = '<button class="btn btn-info" ng-click="selectProperties()" title="Assign this user"><span class="glyphicon glyphicon-user"></span>Assignment</button>'; var compiledHtml = $compile(strElm); element.append(compiledHtml); and don't remove $compile service from directive, and...

AngularJS dynamically call function

javascript,angularjs

seems like you have missed the argument for the controller method in the HTML // you have missed the event parameter. <input type="text" ng-model="value" ng-enter="hideToolTip(event)" /> app.directive('ngEnter', function() { return function(scope, element, attrs) { element.bind("keydown keypress", function(event) { if (event.which === 13) { console.log(attrs.ngEnter); scope.$apply( scope.$eval(attrs.ngEnter, { 'event': event })...

Pre-Select of an option in a select not working

angularjs

Bind value in model to get selected. Try like this $scope.rule.condition=$scope.conditions[0].value; ...

AngularJS factory dependencies

javascript,html,angularjs,mongodb

DOCS Change your factory to service as you are using this factory return an object or primitive type not bind with this app.services('articleFactory', ['$q', '$http', function ($q, $http){ this.getAllArticles = function (){ var deferred = $q.defer(), httpPromise = $http.get ('/entries'); httpPromise.success (function (data){ deferred.resolve (data); }) .error (function (err){ console.log...

Angular ng-repeat cache (avoid re-rendering on state change)

javascript,angularjs,performance,caching,angularjs-ng-repeat

Well if you disable the scope of the scope that the ng-repeat is on. Then it will no longer render. It essentially becomes static content. This allows you to actually control when it is rendered. ux-datagrid actually uses this concept to turn off dom that is out of view so...

HTML elements in Angular bindings expression

html,angularjs

You could use ng-show, it will show the paragraph if employee.firstname is null. <tr ng-repeat="employee in employees"> <td>{{employee.firstname }}<p ng-show="!employee.firstname" style="color:red">No name</p></td> <td>{{employee.job}}</td> </tr> ...

AngularJS, Animate on change: directive $watch not called

javascript,angularjs,angularjs-directive

You need to change the first argument on the $watch, to be a function returning your variable, instead of the variable itself: scope.$watch(function () { return scope.animateWatch; }, function (nv, ov) { call(); }, true); Take a look here at the docs at the watch section....

Angular-strap data-trigger='focus' not working

javascript,html,angularjs,angular-strap

You can add a tabindex attribute to make a <span> focus-able. This also applies for <div> and <table> elements. The tabindex global attribute is an integer indicating if the element can take input focus (is focusable), if it should participate to sequential keyboard navigation, and if so, at what position....

function is undefined if no module is declared in Angular

angularjs

1st one you used is nothing but global function declaration of controller, in which you declare controller as function. To analyse the Angular the function should be treated as controller we need to use post-fix as Controller. The reason it is not working because you are using Angular 1.3 +...

Getting CROS Error even after adding header in node.js for Angular js

javascript,angularjs,node.js

The error message spells it out for you. Your client side code is trying to set an Access-Control-Allow-Origin header: RestangularProvider.setDefaultHeaders({"Access-Control-Allow- Origin":"*"}); Your server side code allows a number of headers, but that isn't one of them: 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept"', Remove the line: RestangularProvider.setDefaultHeaders({"Access-Control-Allow- Origin":"*"}); Access-Control-Allow-Origin is a response...

Getting generic anchor text on click with angularJS/jQuery returns empty string

jquery,angularjs

You are mixing jquery with angular logic with var title = $(this).text(); . You shouldn't try to do this. the $("this") is not referencing what you think it is in that context. You could try logging it to see what I mean. Instead, just pass back the object ng-click="findArticleByTitle(article)" then...

Error: [$injector:unpr] Unknown provider: RestangularProvider <- Restangular <- ctrlAG

javascript,angularjs,restangular

You didn't inject module of 'Restangular' service. Try like this angular.module('AngApp', ['angularGrid','restangular']); ...

Improve slow angular directive

javascript,angularjs,angularjs-directive

The slowness you're experiencing could be due to the fact that after the window has been resized, a digest cycle isn't triggered. The fact that the view changes as all I suspect is due to the fact the digest cycle is later triggered by something else. To fix this, you...

$scope variable does not update within $interval function

javascript,angularjs,angularjs-scope

The problem is probably not using a dot in ng-model. There probably is an inherited scope being created by a parent node which contains the HTML posted in the question. See also: AngularJS: dot in ng-model AngularJS: If you are not using a .(dot) in your models you are doing...

Save to 3 firebase locations with a slow internet connection

javascript,angularjs,firebase,latency

There is no Firebase method to write to multiple paths at once. Some future tools planned by the team (e.g. Triggers) may resolve this in the future. This topic has been explored before and the firebase-multi-write README contains a lot of discussion on the topic. The repo also has a...

Is there a way to fire an event every time an ajax call in made in AngularJS?

javascript,ajax,angularjs,express

In Angular this can be solved with an interceptor. See Angular-loading-bar as example.

Angular submit not called when required fields not filled

javascript,angularjs,forms

You need to add novalidate to your form. The reason being, your browser is validating your form rather than letting your code do it. alternatively, do something like: <form ng-submit="submit()" name="form" novalidate> <ion-radio ng-repeat="item in items" ng-model="data.type" name="type" ng-value="item.value" ng-class="{'error' : form.type.$invalid && form.$submitted }" </form> form.$submitted will become true...

Passing params to an angular service from a controller?

javascript,angularjs,service,controller,params

You can declare your service as: app.factory('books', ['$http', function($http) { // var url = 'http://...' + ParamFromController + '.json' return { getVal: function(url,options){ return $http.get(url,options) } } }]); and use it in your controller and provide appropriate params to pass into 'books' service: app.controller('BookController', ['$scope', '$routeParams', 'books', function($scope, $routeParams, books)...