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];
        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 =
      render json: {success: true}
      render json: @user_file.errors


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

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.

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

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

Related External Links:

- [ng-file-upload wiki - rails example](

Article Topic:Software Development - Javascript

Date:May 17, 2016