Angularjs

File Uploads In AngularJS To A Rails API Using Ng-File-Upload

Posted by Weston Ganger on May 17, 2016

The module ng-file-upload has been a lifesaver for simplifying file uploads with AngularJS.

Here I will describe 2 ways to use it with a Rails backend.


Single file upload.


yourApp.controller('yourCtrl', ['Upload', function(Upload){
  $scope.upload = function(file){
    Upload.upload({
      url: '/user_files/',
      method: 'POST',
      fields: { 
        'user_file[user_id]': currentUserId
      },
      file: file,
      fileFormDataName: 'user_file[image]'
    });
  };
}]);


We can also do a Multi-File upload.


yourApp.controller('yourCtrl', ['Upload', function(Upload){
  $scope.upload = function(files){
    for (var i = 0; i < files.length; i++) {
      var file = files[i];
      Upload.upload({
        url: '/user_files/',
        method: 'POST',
        fields: {
          user_id: currentUserId
        },
        file: file,
        fileFormDataName: 'user_file[image]'
      });
    }
  };
}]);


Heres an example Rails controller. As you can see its the same as it would normally be. I used paperclip gem for the Rails uploads but you can use whatever gem suits you best.


# app/controllers/user_files_controller.rb

class UserFilesController < ApplicationController
  def create
    @user_file = UserFile.new(user_file_params)
    if @user_file.save
      render json: {success: true}
    else
      render json: @user_file.errors
    end  
  end

private 

  def user_file_params
    params.require(:user_file).permit(:image, :user_id)
  end 
end


Now all thats needed is to add a file input to your html. Just adjust this to suit a multi-file upload approach if you like.


<form ng-submit="upload(file)"
  <input type="file" ng-model="file">

  <button type="submit"> Upload </button>
</form>


Related External Links:


Posted in Angular and Tagged with angularjs rails file-upload 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts