How to send files from Javascript/React to a Ruby on Rails API Controller

I saw that a lot of people especially junior developers have problems with sending files from a JavaScript/React frontend to a Ruby on Rails API controller. In this article, we'll walk you through the process of sending a file using the FormData API.

Setting up the frontend

First, let's set up the frontend to handle file uploads. We'll use the FormData API to create a new FormData object, append the file to it and then send it to the server. Here's an example:

async function handleSubmit(formData) {
  const formDataWithFile = new FormData()
  formDataWithFile.append('file', formData.file)
  formDataWithFile.append('extra_param', `extra_value`)

  return await fetch(`api/my_files/upload_file`, {
    method: 'POST',
    body: formDataWithFile,
  });
}

In this example, we create a new FormData object called formDataWithFile. We then attach the file to it using the append method. We can also append any additional data we want to send with the file.
In this case, we're sending an additional parameter called extra_param with a value of extra_value. Finally, we send the FormData object to the server using fetch.

Setting up the backend

Now that we have the frontend set up, let's move on to the backend. To handle file uploads in Ruby on Rails, we need to get params from our controller. Here's an example:

class MyFilesController < ApplicationController
  def upload_file
    params[:file][:tempfile].read.each_line do |line|
      puts line
    end
  end
end

We define a new action called upload_file in the MyFilesController. We then access the file using params[:file]. We can then loop through each line of the file using the each_line method and print it to the console using puts if you want to read text from a txt file for example.

Summary

I believe that the quickstart guide will cover most common cases when you need to add support with handling files from the frontend to your backend.

Happy coding!