Validating File Types with ActionText and ActiveStorage

In my latest Rails app, I’ve started using ActiveStorage and ActionText. Previously, I always used the Paperclip gem for attachments.

With the changes in attachment storage, I needed to learn how to do validations to make sure that users weren’t uploading potential harmful files.

I’m using Trix to allow users to create rich content. Thanks to Saeloin Blog, I found JS that would help validate the file type (see the post for more).

Here’s what I did based on Saeloin Blog’s post.

(1) I created a new file in app/javascript/src/trix-editor-overrides.js

// Limits the file types that can be uploaded in ActionText
// https://blog.saeloun.com/2019/11/12/attachments-in-action-text-rails-6.html

window.addEventListener("trix-file-accept", function(event) {  
const acceptedTypes = ['image/jpeg', 'image/png']  if (!acceptedTypes.includes(event.file.type)) {    event.preventDefault()    alert("Only jpeg or png files can be uploaded")  
}})

(2) I added this line in application.js:

import "src/trix-editor-overrides"

For Active Storage, I used the Active Storage Validations gem, and in my model files, I added:

  validates :image, attached: true,
                    content_type: ['image/png', 'image/jpg']

Rails Paperclip Error: identify ‘-format’ ‘%wx%h’

I was receiving the “identify ‘-format’ ‘%wx%h’ ” error with Paperclip.  The reason is because Paperclip requires ImageMagick if images are manipulated, and the path must be specified for this to happen.  In order to find the path in Windows, what I did was:

  1. open a command prompt (CMD from the start menu)
  2. navigate to c://
  3. type “PATH”
  4. it should show the path(s) that can be used for ImageMagick
  5. I added this line to development.rb

Paperclip.options[:command_path] = “/bin” #(in place of “/bin” put your path)

Restart your server.