Skip to content

Instantly share code, notes, and snippets.

@vajapravin
Last active April 12, 2016 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vajapravin/48059fd9d64bb42f012f513cebd391ea to your computer and use it in GitHub Desktop.
Save vajapravin/48059fd9d64bb42f012f513cebd391ea to your computer and use it in GitHub Desktop.
How to upload image in AngularJS with Rails backend.
# Sorry for not explaining basic stuff
module ApplicationHelper
def decode_base64_image document
if document[:base64] && document[:filetype] && document[:filename]
decoded_data = Base64.decode64(document[:base64])
data = StringIO.new(decoded_data)
data.class_eval do
attr_accessor :content_type, :original_filename
end
data.content_type = document[:filetype]
data.original_filename = File.basename(document[:filename])
data
end
end
end
FooBar.controller('WhateverCtrl', ['$rootScope', '$scope', '$http', function($rootScope, $scope, $http) {
$scope.user = {first_name: '', last_name: '', profile: ''};
$scope.register = function(){
submitForm('/hey/there/here/your/api/user_registeration.json', $scope.user, registerCallback, '#userRegister');
}
submitForm = function(url, params, callback, form){
$http({
url: url,
method: 'POST', // mention your webservice type [POST, PUT]
headers: {'Content-Type': 'application/json'}, // yes, it will work with application/json, don't worry
data: params
}).then(function(response){
if(response.data.success){
callback();
$(form)[0].reset();
$scope.user = {first_name: '', last_name: '', profile: ''};
} else {
// handle your error exception
}
});
}
registerCallback = function(){
// after registration stuff here
}
});
<!--Based in https://github.com/adonespitogo/angular-base64-upload, Thank you to Adones Pitogo -->
<!--form starts-->
<form ng-submit="register()" id='agendaInsertForm'>
<input type='text' ng-model='user.first_name' required/>
<input type='text' ng-model='user.last_name' required/>
<input type='file' ng-model='user.profile' base-sixty-four-input required/>
<input type='submit' value='SAVE' />
</form>
<!--form ends-->
class UserRegistrationController < Admin::BaseController
def create
user = User.create(first_name: params[:first_name], first_name: params[:last_name], profile: decode_base64_image(params[:profile]))
render json: {success: true, message: 'Yeh! You are a rockstar!'}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment