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

Posted By Weston Ganger

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(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.

<pre>
<code class="language-markup">
<form ng-submit="upload(file)"
<input type="file" ng-model="file">

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



Related External Links:

- [ng-file-upload wiki - rails example](https://github.com/danialfarid/ng-file-upload/wiki/Rails-Example)

Article Topic:Software Development - Javascript

Date:May 17, 2016