Uploading files is a common thing that we do on the internet. Uploading images to Instagram, uploading audio files to SoundCloud, uploading videos to Youtube, uploading images to this blog, etc. If you are looking to integrate a feature like this into your React/Rails application, I got you. In this blog I will be using postgresql for the database and I will be dealing with audio files such as mp3, wav, etc. Thanks to Active Storage, the process for doing this is not as complicated as you might think.
Run this in your console:
This will create 2 tables that you can view in your
./db/migrate folder, then run:
If you check your
schema this is what you should see:
Don't worry too much about these for now, I will be linking other helpful blogs at the bottom that explain more in detail about how these tables work under the hood if you want to know more.
This macro will magically associate a file attachment to whatever model you apply it to. In the context of this example, I want a user to be able to upload beats with an audio file attached. You can name the macro whatever you want I just decided to call it
:audio_data (e.g. :audio, :audio_file, :image, :picture, etc) I recommend naming it with a description that matches the type of file you are going to be working with:
- input's accept attribute - we are setting the value to "audio/*" which allows a user to upload all audio file types. Use "image/*" for images and "video/*" for videos.
onChange - with file uploads, they are going to be stored in an array called
files. Because we are only uploading 1 file we just access our file at the  index.
Files require different packaging than your typical
JSON.stringify(). We need to send the body as formData by creating an empty formData object and then appending our state to it. The right side of the comma is our state we had at the top, make sure the left side of the comma matches what you have in your
schema. Don't bother trying to console.log the formData object either, you will just get an empty object.
Clicking that play button is a great feeling. Now go sicko mode and unleash your new file uploading powers!! Below are resources that really helped me accomplish this, please let me know in the comments below if there is anything important I may have left out.
HTML input accept Attribute - W3Schools
FormData() - MDN
Using FormData Objects - MDN
How to upload mp3s to your rails backend using active storage
React File Uploads to Rails
Upload images to your Rails API from React the easy way
React Audio Player