Javascript required
Skip to content Skip to sidebar Skip to footer

How Do I Upload a File to a Rails App and Add the Data to My Database?

Agile Storage Overview

This guide covers how to attach files to your Active Tape models.

Subsequently reading this guide, y'all will know:

  • How to adhere one or many files to a record.
  • How to delete an attached file.
  • How to link to an attached file.
  • How to apply variants to transform images.
  • How to generate an paradigm representation of a non-prototype file, such as a PDF or a video.
  • How to send file uploads straight from browsers to a storage service, bypassing your application servers.
  • How to clean up files stored during testing.
  • How to implement support for additional storage services.

Capacity

  1. What is Active Storage?
    • Requirements
  2. Setup
    • Disk Service
    • S3 Service (Amazon S3 and S3-uniform APIs)
    • Microsoft Azure Storage Service
    • Google Deject Storage Service
    • Mirror Service
    • Public access
  3. Attaching Files to Records
    • has_one_attached
    • has_many_attached
    • Attaching File/IO Objects
  4. Removing Files
  5. Serving Files
    • Redirect style
    • Proxy manner
    • Authenticated Controllers
  6. Downloading Files
  7. Analyzing Files
  8. Displaying Images, Videos, and PDFs
    • Lazy vs Immediate Loading
    • Transforming Images
    • Previewing Files
  9. Directly Uploads
    • Usage
    • Cross-Origin Resources Sharing (CORS) configuration
    • Direct upload JavaScript events
    • Example
    • Integrating with Libraries or Frameworks
  10. Testing
    • Discarding files created during tests
    • Calculation attachments to fixtures
  11. Implementing Back up for Other Cloud Services
  12. Purging Unattached Uploads

ane What is Active Storage?

Active Storage facilitates uploading files to a cloud storage service like Amazon S3, Google Cloud Storage, or Microsoft Azure Storage and attaching those files to Active Tape objects. It comes with a local disk-based service for evolution and testing and supports mirroring files to subordinate services for backups and migrations.

Using Active Storage, an application can transform image uploads or generate image representations of non-epitome uploads like PDFs and videos, and extract metadata from arbitrary files.

1.ane Requirements

Various features of Active Storage depend on third-political party software which Rails will non install, and must be installed separately:

  • libvips v8.6+ or ImageMagick for image analysis and transformations
  • ffmpeg v3.4+ for video previews and ffprobe for video/audio analysis
  • poppler or muPDF for PDF previews

Image assay and transformations also require the image_processing gem. Uncomment it in your Gemfile, or add it if necessary:

                          precious stone              "image_processing"              ,              ">= 1.2"                      

Compared to libvips, ImageMagick is better known and more widely available. Notwithstanding, libvips tin can be up to 10x faster and consume one/10 the memory. For JPEG files, this tin can be further improved by replacing libjpeg-dev with libjpeg-turbo-dev, which is 2-7x faster.

Before y'all install and employ 3rd-party software, make sure you empathize the licensing implications of doing so. MuPDF, in particular, is licensed nether AGPL and requires a commercial license for some use.

2 Setup

Active Storage uses three tables in your application's database named active_storage_blobs, active_storage_variant_records and active_storage_attachments. After creating a new application (or upgrading your application to Rails 5.2), run bin/rails active_storage:install to generate a migration that creates these tables. Use bin/rails db:migrate to run the migration.

active_storage_attachments is a polymorphic bring together table that stores your model's class name. If your model's class proper noun changes, you will need to run a migration on this table to update the underlying record_type to your model's new form proper noun.

If you are using UUIDs instead of integers equally the primary cardinal on your models you will need to change the column blazon of active_storage_attachments.record_id and active_storage_variant_records.id in the generated migration accordingly.

Declare Agile Storage services in config/storage.yml. For each service your application uses, provide a proper noun and the requisite configuration. The case below declares 3 services named local, test, and amazon:

                          local              :              service              :              Disk              root              :              <%= Rails.root.join("storage") %>              test              :              service              :              Disk              root              :              <%= Rails.root.bring together("tmp/storage") %>              amazon              :              service              :              S3              access_key_id              :              "              "              secret_access_key              :              "              "              bucket              :              "              "              region              :              "              "              # east.grand. 'us-eastward-one'                      

Tell Active Storage which service to use by setting Rails.application.config.active_storage.service. Considering each environment will probable utilize a different service, it is recommended to do this on a per-environment ground. To apply the disk service from the previous instance in the evolution environment, you would add together the following to config/environments/evolution.rb:

                          # Shop files locally.              config              .              active_storage              .              service              =              :local                      

To use the S3 service in production, you add the following to config/environments/production.rb:

                          # Store files on Amazon S3.              config              .              active_storage              .              service              =              :amazon                      

To use the test service when testing, you add the post-obit to config/environments/test.rb:

                          # Store uploaded files on the local file organization in a temporary directory.              config              .              active_storage              .              service              =              :examination                      

Continue reading for more information on the congenital-in service adapters (e.g. Deejay and S3) and the configuration they require.

Configuration files that are surroundings-specific volition have precedence: in production, for instance, the config/storage/production.yml file (if existent) will have precedence over the config/storage.yml file.

It is recommended to use Rails.env in the bucket names to farther reduce the risk of accidentally destroying product information.

                          amazon              :              service              :              S3              # ...              bucket              :              your_own_bucket-<%= Rails.env %>              google              :              service              :              GCS              # ...              bucket              :              your_own_bucket-<%= Rails.env %>              azure              :              service              :              AzureStorage              # ...              container              :              your_container_name-<%= Track.env %>                      

two.1 Disk Service

Declare a Disk service in config/storage.yml:

                          local              :              service              :              Disk              root              :              <%= Rails.root.bring together("storage") %>                      

2.2 S3 Service (Amazon S3 and S3-compatible APIs)

To connect to Amazon S3, declare an S3 service in config/storage.yml:

                          amazon              :              service              :              S3              access_key_id              :              "              "              secret_access_key              :              "              "              region              :              "              "              saucepan              :              "              "                      

Optionally provide customer and upload options:

                          amazon              :              service              :              S3              access_key_id              :              "              "              secret_access_key              :              "              "              region              :              "              "              bucket              :              "              "              http_open_timeout              :              0              http_read_timeout              :              0              retry_limit              :              0              upload              :              server_side_encryption              :              "              "              # 'aws:kms' or 'AES256'                      

Set sensible client HTTP timeouts and retry limits for your application. In certain failure scenarios, the default AWS customer configuration may cause connections to exist held for up to several minutes and lead to asking queuing.

Add together the aws-sdk-s3 gem to your Gemfile:

                          gem              "aws-sdk-s3"              ,              crave:                            faux                      

The core features of Active Storage require the following permissions: s3:ListBucket, s3:PutObject, s3:GetObject, and s3:DeleteObject. Public admission additionally requires s3:PutObjectAcl. If yous accept boosted upload options configured such as setting ACLs so boosted permissions may exist required.

If you want to use surroundings variables, standard SDK configuration files, profiles, IAM example profiles or task roles, you tin omit the access_key_id, secret_access_key, and region keys in the instance above. The S3 Service supports all of the authentication options described in the AWS SDK documentation.

To connect to an S3-compatible object storage API such as DigitalOcean Spaces, provide the endpoint:

                          digitalocean              :              service              :              S3              endpoint              :              https://nyc3.digitaloceanspaces.com              access_key_id              :              ...              secret_access_key              :              ...              # ...and other options                      

There are many other options available. You tin check them in AWS S3 Customer documentation.

2.3 Microsoft Azure Storage Service

Declare an Azure Storage service in config/storage.yml:

                          azure              :              service              :              AzureStorage              storage_account_name              :              "              "              storage_access_key              :              "              "              container              :              "              "                      

Add together the azure-storage-blob gem to your Gemfile:

                          gem              "azure-storage-blob"              ,              require:                            imitation                      

ii.4 Google Cloud Storage Service

Declare a Google Cloud Storage service in config/storage.yml:

                          google              :              service              :              GCS              credentials              :              <%= Rails.root.bring together("path/to/keyfile.json") %>              project              :              "              "              bucket              :              "              "                      

Optionally provide a Hash of credentials instead of a keyfile path:

                          google              :              service              :              GCS              credentials              :              type              :              "              service_account"              project_id              :              "              "              private_key_id              :              <%= Runway.application.credentials.dig(:gcs, :private_key_id) %>              private_key              :              <%= Rail.awarding.credentials.dig(:gcs, :private_key).dump %>              client_email              :              "              "              client_id              :              "              "              auth_uri              :              "              https://accounts.google.com/o/oauth2/auth"              token_uri              :              "              https://accounts.google.com/o/oauth2/token"              auth_provider_x509_cert_url              :              "              https://www.googleapis.com/oauth2/v1/certs"              client_x509_cert_url              :              "              "              project              :              "              "              saucepan              :              "              "                      

Optionally provide a Cache-Control metadata to gear up on uploaded avails:

                          google              :              service              :              GCS              ...              cache_control              :              "              public,                                          max-age=3600"                      

Optionally use IAM instead of the credentials when signing URLs. This is useful if you are authenticating your GKE applications with Workload Identity, encounter this Google Cloud blog post for more information.

                          google              :              service              :              GCS              ...              iam              :              true                      

Optionally employ a specific GSA when signing URLs. When using IAM, the metadata server will exist contacted to go the GSA email, but this metadata server is non always present (eastward.thou. local tests) and you may wish to use a non-default GSA.

                          google              :              service              :              GCS              ...              iam              :              true              gsa_email              :              "              foobar@baz.iam.gserviceaccount.com"                      

Add together the google-cloud-storage gem to your Gemfile:

                          gem              "google-cloud-storage"              ,              "~> 1.11"              ,              crave:                            simulated                      

2.5 Mirror Service

Yous can keep multiple services in sync by defining a mirror service. A mirror service replicates uploads and deletes beyond two or more subordinate services.

A mirror service is intended to be used temporarily during a migration betwixt services in production. You lot can showtime mirroring to a new service, copy pre-existing files from the onetime service to the new, then go all-in on the new service.

Mirroring is not atomic. It is possible for an upload to succeed on the principal service and neglect on any of the subordinate services. Earlier going all-in on a new service, verify that all files have been copied.

Ascertain each of the services y'all'd similar to mirror as described above. Reference them by name when defining a mirror service:

                          s3_west_coast              :              service              :              S3              access_key_id              :              "              "              secret_access_key              :              "              "              region              :              "              "              bucket              :              "              "              s3_east_coast              :              service              :              S3              access_key_id              :              "              "              secret_access_key              :              "              "              region              :              "              "              saucepan              :              "              "              production              :              service              :              Mirror              primary              :              s3_east_coast              mirrors              :              -              s3_west_coast                      

Although all secondary services receive uploads, downloads are e'er handled by the primary service.

Mirror services are uniform with direct uploads. New files are straight uploaded to the primary service. When a directly-uploaded file is attached to a record, a groundwork task is enqueued to copy it to the secondary services.

2.half dozen Public access

By default, Active Storage assumes individual access to services. This means generating signed, single-employ URLs for blobs. If you'd rather brand blobs publicly accessible, specify public: true in your app's config/storage.yml:

                          gcs              :              &gcs              service              :              GCS              project              :              "              "              private_gcs              :              <<              :              *gcs              credentials              :              <%= Rails.root.join("path/to/private_keyfile.json") %>              bucket              :              "              "              public_gcs              :              <<              :              *gcs              credentials              :              <%= Rails.root.join("path/to/public_keyfile.json") %>              bucket              :              "              "              public              :              truthful                      

Make certain your buckets are properly configured for public admission. See docs on how to enable public read permissions for Amazon S3, Google Cloud Storage, and Microsoft Azure storage services. Amazon S3 additionally requires that you have the s3:PutObjectAcl permission.

When converting an existing awarding to apply public: true, make sure to update every individual file in the bucket to exist publicly-readable before switching over.

3 Attaching Files to Records

3.i has_one_attached

The has_one_attached macro sets up a 1-to-ane mapping between records and files. Each record can have one file attached to information technology.

For example, suppose your application has a User model. If you want each user to accept an avatar, define the User model as follows:

                          grade              User              <              ApplicationRecord              has_one_attached              :avatar              stop                      

or if you are using Rails 6.0+, you can run a model generator control similar this:

                          bin              /              rails              generate              model              User              avatar              :attachment                      

Y'all can create a user with an avatar:

                          <%=              form              .              file_field              :avatar              %>                      
                          class              SignupController              <              ApplicationController              def              create              user              =              User              .              create!              (              user_params              )              session              [              :user_id              ]              =              user              .              id              redirect_to              root_path              end              private              def              user_params              params              .              require              (              :user              ).              permit              (              :email_address              ,              :password              ,              :avatar              )              terminate              end                      

Call avatar.attach to attach an avatar to an existing user:

                          user              .              avatar              .              attach              (              params              [              :avatar              ])                      

Telephone call avatar.attached? to make up one's mind whether a particular user has an avatar:

In some cases y'all might desire to override a default service for a specific attachment. You lot can configure specific services per attachment using the service selection:

                          form              User              <              ApplicationRecord              has_one_attached              :avatar              ,              service: :s3              terminate                      

You tin configure specific variants per attachment by calling the variant method on yielded attachable object:

                          course              User              <              ApplicationRecord              has_one_attached              :avatar              do              |              attachable              |              attachable              .              variant              :thumb              ,              resize_to_limit:                            [              100              ,              100              ]              stop              end                      

Call avatar.variant(:thumb) to become a thumb variant of an avatar:

                          <%=              image_tag              user              .              avatar              .              variant              (              :thumb              )              %>                      

iii.2 has_many_attached

The has_many_attached macro sets up a ane-to-many relationship betwixt records and files. Each tape can have many files attached to it.

For case, suppose your awarding has a Message model. If y'all desire each bulletin to accept many images, define the Message model as follows:

                          class              Message              <              ApplicationRecord              has_many_attached              :images              cease                      

or if you are using Rails six.0+, y'all can run a model generator command like this:

                          bin              /              runway              generate              model              Bulletin              images              :attachments                      

You tin create a message with images:

                          class              MessagesController              <              ApplicationController              def              create              message              =              Message              .              create!              (              message_params              )              redirect_to              message              end              private              def              message_params              params              .              crave              (              :message              ).              permit              (              :title              ,              :content              ,              images:                            [])              cease              end                      

Call images.attach to add together new images to an existing message:

                          @message              .              images              .              attach              (              params              [              :images              ])                      

Call images.attached? to make up one's mind whether a particular message has whatever images:

                          @message              .              images              .              fastened?                      

Overriding the default service is done the same way as has_one_attached, by using the service option:

                          class              Bulletin              <              ApplicationRecord              has_many_attached              :images              ,              service: :s3              end                      

Configuring specific variants is washed the aforementioned style as has_one_attached, by calling the variant method on the yielded attachable object:

                          class              Bulletin              <              ApplicationRecord              has_many_attached              :images              do              |              attachable              |              attachable              .              variant              :pollex              ,              resize_to_limit:                            [              100              ,              100              ]              finish              finish                      

3.3 Attaching File/IO Objects

Sometimes you lot need to adhere a file that doesn't arrive via an HTTP request. For example, you may want to attach a file you generated on deejay or downloaded from a user-submitted URL. Y'all may also want to attach a fixture file in a model examination. To do that, provide a Hash containing at least an open IO object and a filename:

                          @message              .              images              .              adhere              (              io:                            File              .              open              (              '/path/to/file'              ),              filename:                            'file.pdf'              )                      

When possible, provide a content type besides. Agile Storage attempts to determine a file's content blazon from its information. It falls back to the content type you provide if information technology tin't do that.

                          @bulletin              .              images              .              adhere              (              io:                            File              .              open              (              '/path/to/file'              ),              filename:                            'file.pdf'              ,              content_type:                            'application/pdf'              )                      

You can bypass the content type inference from the information past passing in identify: fake along with the content_type.

                          @message              .              images              .              attach              (              io:                            File              .              open              (              '/path/to/file'              ),              filename:                            'file.pdf'              ,              content_type:                            'awarding/pdf'              ,              identify:                            fake              )                      

If y'all don't provide a content type and Agile Storage tin't determine the file's content type automatically, information technology defaults to awarding/octet-stream.

4 Removing Files

To remove an attachment from a model, call purge on the attachment. If your application is prepare to utilise Agile Job, removal can be done in the groundwork instead past calling purge_later. Purging deletes the blob and the file from the storage service.

                          # Synchronously destroy the avatar and actual resource files.              user              .              avatar              .              purge              # Destroy the associated models and actual resource files async, via Agile Job.              user              .              avatar              .              purge_later                      

5 Serving Files

Active Storage supports two means to serve files: redirecting and proxying.

All Agile Storage controllers are publicly accessible by default. The generated URLs are hard to guess, but permanent by blueprint. If your files require a higher level of protection consider implementing Authenticated Controllers.

five.1 Redirect mode

To generate a permanent URL for a hulk, you can pass the blob to the url_for view helper. This generates a URL with the blob's signed_id that is routed to the blob's RedirectController

                          url_for              (              user              .              avatar              )              # => /track/active_storage/blobs/:signed_id/my-avatar.png                      

The RedirectController redirects to the actual service endpoint. This indirection decouples the service URL from the actual one, and allows, for case, mirroring attachments in unlike services for high-availability. The redirection has an HTTP expiration of 5 minutes.

To create a download link, use the rails_blob_{path|url} helper. Using this helper allows you to set the disposition.

                          rails_blob_path              (              user              .              avatar              ,              disposition:                            "attachment"              )                      

To preclude XSS attacks, Active Storage forces the Content-Disposition header to "attachment" for some kind of files. To change this behaviour come across the bachelor configuration options in Configuring Rails Applications.

If you demand to create a link from outside of controller/view context (Groundwork jobs, Cronjobs, etc.), you lot can access the rails_blob_path like this:

                          Rails              .              application              .              routes              .              url_helpers              .              rails_blob_path              (              user              .              avatar              ,              only_path:                            truthful              )                      

v.ii Proxy manner

Optionally, files can be proxied instead. This means that your awarding servers will download file data from the storage service in response to requests. This can exist useful for serving files from a CDN.

You can configure Active Storage to use proxying past default:

                          # config/initializers/active_storage.rb              Rails              .              application              .              config              .              active_storage              .              resolve_model_to_route              =              :rails_storage_proxy                      

Or if you want to explicitly proxy specific attachments there are URL helpers you can use in the grade of rails_storage_proxy_path and rails_storage_proxy_url.

                          <%=              image_tag              rails_storage_proxy_path              (              @user              .              avatar              )              %>                      
5.ii.1 Putting a CDN in front of Agile Storage

Additionally, in order to use a CDN for Active Storage attachments, you will need to generate URLs with proxy style so that they are served past your app and the CDN will cache the zipper without any extra configuration. This works out of the box because the default Active Storage proxy controller sets an HTTP header indicating to the CDN to cache the response.

You should also make sure that the generated URLs use the CDN host instead of your app host. In that location are multiple ways to achieve this, but in general information technology involves tweaking your config/routes.rb file and then that you can generate the proper URLs for the attachments and their variations. As an example, you could add together this:

                          # config/routes.rb              direct              :cdn_image              do              |              model              ,              options              |              expires_in              =              options              .              delete              (              :expires_in              )              {              ActiveStorage              .              urls_expire_in              }              if              model              .              respond_to?              (              :signed_id              )              route_for              (              :rails_service_blob_proxy              ,              model              .              signed_id              (              expires_in:                            expires_in              ),              model              .              filename              ,              options              .              merge              (              host:                            ENV              [              'CDN_HOST'              ])              )              else              signed_blob_id              =              model              .              hulk              .              signed_id              (              expires_in:                            expires_in              )              variation_key              =              model              .              variation              .              key              filename              =              model              .              blob              .              filename              route_for              (              :rails_blob_representation_proxy              ,              signed_blob_id              ,              variation_key              ,              filename              ,              options              .              merge              (              host:                            ENV              [              'CDN_HOST'              ])              )              stop              end                      

and and then generate routes similar this:

                          <%=              cdn_image_url              (              user              .              avatar              .              variant              (              resize_to_limit:                            [              128              ,              128              ]))              %>                      

five.three Authenticated Controllers

All Active Storage controllers are publicly attainable past default. The generated URLs utilise a apparently signed_id, making them hard to estimate simply permanent. Anyone that knows the hulk URL will exist able to access it, even if a before_action in your ApplicationController would otherwise crave a login. If your files require a higher level of protection, yous tin can implement your ain authenticated controllers, based on the ActiveStorage::Blobs::RedirectController, ActiveStorage::Blobs::ProxyController, ActiveStorage::Representations::RedirectController and ActiveStorage::Representations::ProxyController

To just allow an account to access their own logo you could practise the following:

                          # config/routes.rb              resources              :account              practice              resource              :logo              stop                      
                          # app/controllers/logos_controller.rb              form              LogosController              <              ApplicationController              # Through ApplicationController:              # include Authenticate, SetCurrentAccount              def              evidence              redirect_to              Current              .              account              .              logo              .              url              end              end                      
                          <%=              image_tag              account_logo_path              %>                      

And then you might want to disable the Active Storage default routes with:

                          config              .              active_storage              .              draw_routes              =              imitation                      

to prevent files being accessed with the publicly accessible URLs.

6 Downloading Files

Sometimes you lot need to process a hulk afterward it's uploaded—for instance, to convert it to a different format. Use the attachment's download method to read a blob'south binary information into memory:

                          binary              =              user              .              avatar              .              download                      

You might want to download a blob to a file on disk so an external program (due east.k. a virus scanner or media transcoder) can operate on it. Use the zipper'south open method to download a blob to a tempfile on disk:

                          message              .              video              .              open up              do              |              file              |              organization              '/path/to/virus/scanner'              ,              file              .              path              # ...              end                      

Information technology's of import to know that the file is not all the same bachelor in the after_create callback but in the after_create_commit but.

seven Analyzing Files

Active Storage analyzes files one time they've been uploaded past queuing a chore in Agile Job. Analyzed files will store additional information in the metadata hash, including analyzed: true. You can check whether a blob has been analyzed by calling analyzed? on it.

Image analysis provides width and height attributes. Video analysis provides these, as well as duration, bending, display_aspect_ratio, and video and sound booleans to indicate the presence of those channels. Audio analysis provides duration and bit_rate attributes.

8 Displaying Images, Videos, and PDFs

Agile Storage supports representing a multifariousness of files. You can call representation on an attachment to display an prototype variant, or a preview of a video or PDF. Earlier calling representation, check if the attachment can be represented by calling representable?. Some file formats can't exist previewed by Active Storage out of the box (due east.k. Word documents); if representable? returns fake you may want to link to the file instead.

                          <ul>              <%              @message              .              files              .              each              do              |              file              |              %>              <li>              <%              if              file              .              representable?              %>              <%=              image_tag              file              .              representation              (              resize_to_limit:                            [              100              ,              100              ])              %>              <%              else              %>              <%=              link_to              rails_blob_path              (              file              ,              disposition:                            "attachment"              )              do              %>              <%=              image_tag              "placeholder.png"              ,              alt:                            "Download file"              %>              <%              end              %>              <%              terminate              %>              </li>              <%              end              %>              </ul>                      

Internally, representation calls variant for images, and preview for previewable files. Yous tin also call these methods straight.

8.1 Lazy vs Immediate Loading

Past default, Active Storage will process representations lazily. This lawmaking:

                          image_tag              file              .              representation              (              resize_to_limit:                            [              100              ,              100              ])                      

Will generate an <img> tag with the src pointing to the ActiveStorage::Representations::RedirectController. The browser will make a request to that controller, which volition return a 302 redirect to the file on the remote service (or in proxy way, return the file contents). Loading the file lazily allows features similar unmarried utilize URLs to piece of work without slowing downwards your initial page loads.

This works fine for almost cases.

If you lot want to generate URLs for images immediately, you can call .processed.url:

                          image_tag              file              .              representation              (              resize_to_limit:                            [              100              ,              100              ]).              candy              .              url                      

The Active Storage variant tracker improves functioning of this, by storing a tape in the database if the requested representation has been processed before. Thus, the to a higher place code volition simply brand an API phone call to the remote service (e.g. S3) in one case, and once a variant is stored, will utilize that. The variant tracker runs automatically, only tin be disabled through config.active_storage.track_variants.

If you're rendering lots of images on a page, the above example could result in N+1 queries loading all the variant records. To avoid these Northward+1 queries, employ the named scopes on ActiveStorage::Attachment.

                          bulletin              .              images              .              with_all_variant_records              .              each              practice              |              file              |              image_tag              file              .              representation              (              resize_to_limit:                            [              100              ,              100              ]).              processed              .              url              end                      

eight.2 Transforming Images

Transforming images allows you to display the epitome at your choice of dimensions. To create a variation of an image, call variant on the attachment. You tin pass whatsoever transformation supported by the variant processor to the method. When the browser hits the variant URL, Active Storage volition lazily transform the original blob into the specified format and redirect to its new service location.

                          <%=              image_tag              user              .              avatar              .              variant              (              resize_to_limit:                            [              100              ,              100              ])              %>                      

If a variant is requested, Active Storage will automatically apply transformations depending on the prototype'southward format:

  1. Content types that are variable (equally dictated by config.active_storage.variable_content_types) and not considered web images (as dictated by config.active_storage.web_image_content_types), will be converted to PNG.

  2. If quality is not specified, the variant processor's default quality for the format will be used.

Active Storage can apply either Vips or MiniMagick as the variant processor. The default depends on your config.load_defaults target version, and the processor tin be changed by setting config.active_storage.variant_processor.

The ii processors are not fully compatible, so when migrating an existing application between MiniMagick and Vips, some changes have to be fabricated if using options that are format specific:

                          <!-- MiniMagick -->              <%=              image_tag              user              .              avatar              .              variant              (              resize_to_limit:                            [              100              ,              100              ],              format: :jpeg              ,              sampling_factor:                            "4:2:0"              ,              strip:                            true              ,              interlace:                            "JPEG"              ,              colorspace:                            "sRGB"              ,              quality:                            lxxx              )              %>              <!-- Vips -->              <%=              image_tag              user              .              avatar              .              variant              (              resize_to_limit:                            [              100              ,              100              ],              format: :jpeg              ,              saver:                            {              subsample_mode:                            "on"              ,              strip:                            true              ,              interlace:                            true              ,              quality:                            fourscore              })              %>                      

viii.3 Previewing Files

Some non-epitome files tin can be previewed: that is, they tin can exist presented as images. For case, a video file can exist previewed by extracting its beginning frame. Out of the box, Agile Storage supports previewing videos and PDF documents. To create a link to a lazily-generated preview, apply the attachment'due south preview method:

                          <%=              image_tag              message              .              video              .              preview              (              resize_to_limit:                            [              100              ,              100              ])              %>                      

To add support for some other format, add your own previewer. See the ActiveStorage::Preview documentation for more than information.

9 Direct Uploads

Active Storage, with its included JavaScript library, supports uploading directly from the customer to the deject.

nine.i Usage

  1. Include activestorage.js in your awarding'south JavaScript bundle.

    Using the asset pipeline:

                                      //= crave activestorage                              

    Using the npm bundle:

                                      import                  *                  equally                  ActiveStorage                  from                  "                  @rails/activestorage                  "                  ActiveStorage                  .                  start                  ()                              
  2. Add direct_upload: true to your file field:

                                      <%=                  form                  .                  file_field                  :attachments                  ,                  multiple:                                    true                  ,                  direct_upload:                                    true                  %>                              

    Or, if you aren't using a FormBuilder, add the data attribute directly:

                                      <input                  type=                  file                  data-direct-upload-url=                  "                  <%=                  rails_direct_uploads_url                  %>                  "                  />                              
  3. Configure CORS on third-party storage services to allow direct upload requests.

  4. That's it! Uploads brainstorm upon form submission.

9.2 Cross-Origin Resources Sharing (CORS) configuration

To make direct uploads to a third-party service work, you'll need to configure the service to permit cantankerous-origin requests from your app. Consult the CORS documentation for your service:

  • S3
  • Google Deject Storage
  • Azure Storage

Take care to allow:

  • All origins from which your app is accessed
  • The PUT asking method
  • The following headers:
    • Origin
    • Content-Blazon
    • Content-MD5
    • Content-Disposition (except for Azure Storage)
    • x-ms-blob-content-disposition (for Azure Storage only)
    • x-ms-blob-type (for Azure Storage only)
    • Cache-Control (for GCS, only if cache_control is set)

No CORS configuration is required for the Disk service since it shares your app's origin.

9.2.1 Case: S3 CORS configuration
                          [                                          {                                          "AllowedHeaders"              :                                          [                                          "*"                                          ],                                          "AllowedMethods"              :                                          [                                          "PUT"                                          ],                                          "AllowedOrigins"              :                                          [                                          "https://www.example.com"                                          ],                                          "ExposeHeaders"              :                                          [                                          "Origin"              ,                                          "Content-Type"              ,                                          "Content-MD5"              ,                                          "Content-Disposition"                                          ],                                          "MaxAgeSeconds"              :                                          3600                                          }                                          ]                                                  
9.two.two Example: Google Cloud Storage CORS configuration
                          [                                          {                                          "origin"              :                                          [              "https://www.example.com"              ],                                          "method"              :                                          [              "PUT"              ],                                          "responseHeader"              :                                          [              "Origin"              ,                                          "Content-Type"              ,                                          "Content-MD5"              ,                                          "Content-Disposition"              ],                                          "maxAgeSeconds"              :                                          3600                                          }                                          ]                                                  
ix.two.three Example: Azure Storage CORS configuration
                          <Cors>              <CorsRule>              <AllowedOrigins>https://www.instance.com</AllowedOrigins>              <AllowedMethods>PUT</AllowedMethods>              <AllowedHeaders>Origin, Content-Type, Content-MD5, x-ms-hulk-content-disposition, x-ms-blob-type</AllowedHeaders>              <MaxAgeInSeconds>3600</MaxAgeInSeconds>              </CorsRule>              </Cors>                      

9.3 Direct upload JavaScript events

Consequence name Outcome target Event information (upshot.detail) Description
directly-uploads:start <form> None A class containing files for direct upload fields was submitted.
direct-upload:initialize <input> {id, file} Dispatched for every file afterward grade submission.
direct-upload:start <input> {id, file} A direct upload is starting.
direct-upload:earlier-hulk-request <input> {id, file, xhr} Before making a request to your application for direct upload metadata.
direct-upload:earlier-storage-asking <input> {id, file, xhr} Earlier making a request to store a file.
direct-upload:progress <input> {id, file, progress} Every bit requests to shop files progress.
straight-upload:error <input> {id, file, mistake} An error occurred. An alert will display unless this event is canceled.
direct-upload:end <input> {id, file} A direct upload has ended.
direct-uploads:end <form> None All direct uploads have ended.

9.4 Case

You can use these events to evidence the progress of an upload.

direct-uploads

To evidence the uploaded files in a form:

                          // direct_uploads.js              addEventListener              (              "              direct-upload:initialize              "              ,              event              =>              {              const              {              target              ,              detail              }              =              event              const              {              id              ,              file              }              =              detail              target              .              insertAdjacentHTML              (              "              beforebegin              "              ,              `     <div id="directly-upload-              ${              id              }              " form="directly-upload direct-upload--awaiting">       <div id="straight-upload-progress-              ${              id              }              " course="straight-upload__progress" fashion="width: 0%"></div>       <span course="direct-upload__filename"></span>     </div>   `              )              target              .              previousElementSibling              .              querySelector              (              `.direct-upload__filename`              ).              textContent              =              file              .              name              })              addEventListener              (              "              directly-upload:first              "              ,              consequence              =>              {              const              {              id              }              =              event              .              detail              const              element              =              certificate              .              getElementById              (              `direct-upload-              ${              id              }              `              )              element              .              classList              .              remove              (              "              direct-upload--awaiting              "              )              })              addEventListener              (              "              direct-upload:progress              "              ,              issue              =>              {              const              {              id              ,              progress              }              =              event              .              detail              const              progressElement              =              document              .              getElementById              (              `straight-upload-progress-              ${              id              }              `              )              progressElement              .              way              .              width              =              `              ${              progress              }              %`              })              addEventListener              (              "              direct-upload:error              "              ,              event              =>              {              event              .              preventDefault              ()              const              {              id              ,              error              }              =              event              .              detail              const              element              =              certificate              .              getElementById              (              `direct-upload-              ${              id              }              `              )              element              .              classList              .              add              (              "              directly-upload--error              "              )              element              .              setAttribute              (              "              title              "              ,              mistake              )              })              addEventListener              (              "              directly-upload:end              "              ,              event              =>              {              const              {              id              }              =              outcome              .              detail              const              element              =              certificate              .              getElementById              (              `direct-upload-              ${              id              }              `              )              chemical element              .              classList              .              add              (              "              straight-upload--consummate              "              )              })                      

Add together styles:

                          /* direct_uploads.css */              .direct-upload              {              display              :              inline-block              ;              position              :              relative              ;              padding              :              2px              4px              ;              margin              :              0              3px              3px              0              ;              border              :              1px              solid              rgba              (              0              ,              0              ,              0              ,              0.3              );              border-radius              :              3px              ;              font-size              :              11px              ;              line-height              :              13px              ;              }              .direct-upload--pending              {              opacity              :              0.6              ;              }              .direct-upload__progress              {              position              :              absolute              ;              top              :              0              ;              left              :              0              ;              bottom              :              0              ;              opacity              :              0.ii              ;              groundwork              :              #0076ff              ;              transition              :              width              120ms              ease-out              ,              opacity              60ms              60ms              ease-in              ;              transform              :              translate3d              (              0              ,              0              ,              0              );              }              .direct-upload--complete              .direct-upload__progress              {              opacity              :              0.4              ;              }              .direct-upload--fault              {              border-color              :              red              ;              }              input              [              blazon              =              file              ][              information-direct-upload-url              ][              disabled              ]              {              display              :              none              ;              }                      

9.five Integrating with Libraries or Frameworks

If you want to use the Direct Upload feature from a JavaScript framework, or you lot want to integrate custom drag and drop solutions, you can use the DirectUpload course for this purpose. Upon receiving a file from your library of choice, instantiate a DirectUpload and call its create method. Create takes a callback to invoke when the upload completes.

                          import              {              DirectUpload              }              from              "              @runway/activestorage              "              const              input              =              document              .              querySelector              (              '              input[type=file]              '              )              // Bind to file drop - use the ondrop on a parent chemical element or use a              //  library like Dropzone              const              onDrop              =              (              event              )              =>              {              event              .              preventDefault              ()              const              files              =              issue              .              dataTransfer              .              files              ;              Array              .              from              (              files              ).              forEach              (              file              =>              uploadFile              (              file              ))              }              // Bind to normal file selection              input              .              addEventListener              (              '              alter              '              ,              (              upshot              )              =>              {              Array              .              from              (              input              .              files              ).              forEach              (              file              =>              uploadFile              (              file              ))              // you might clear the selected files from the input              input              .              value              =              null              })              const              uploadFile              =              (              file              )              =>              {              // your form needs the file_field direct_upload: true, which              //  provides information-direct-upload-url              const              url              =              input              .              dataset              .              directUploadUrl              const              upload              =              new              DirectUpload              (              file              ,              url              )              upload              .              create              ((              error              ,              blob              )              =>              {              if              (              fault              )              {              // Handle the fault              }              else              {              // Add an appropriately-named hidden input to the form with a              //  value of blob.signed_id so that the blob ids volition be              //  transmitted in the normal upload flow              const              hiddenField              =              document              .              createElement              (              '              input              '              )              hiddenField              .              setAttribute              (              "              type              "              ,              "              subconscious              "              );              hiddenField              .              setAttribute              (              "              value              "              ,              blob              .              signed_id              );              hiddenField              .              name              =              input              .              name              document              .              querySelector              (              '              class              '              ).              appendChild              (              hiddenField              )              }              })              }                      

If you need to track the progress of the file upload, you tin pass a tertiary parameter to the DirectUpload constructor. During the upload, DirectUpload volition call the object'due south directUploadWillStoreFileWithXHR method. You tin can and then bind your ain progress handler on the XHR.

                          import              {              DirectUpload              }              from              "              @rails/activestorage              "              class              Uploader              {              constructor              (              file              ,              url              )              {              this              .              upload              =              new              DirectUpload              (              this              .              file              ,              this              .              url              ,              this              )              }              upload              (              file              )              {              this              .              upload              .              create              ((              fault              ,              blob              )              =>              {              if              (              error              )              {              // Handle the error              }              else              {              // Add an appropriately-named hidden input to the form              // with a value of blob.signed_id              }              })              }              directUploadWillStoreFileWithXHR              (              request              )              {              request              .              upload              .              addEventListener              (              "              progress              "              ,              event              =>              this              .              directUploadDidProgress              (              event              ))              }              directUploadDidProgress              (              event              )              {              // Utilize effect.loaded and event.total to update the progress bar              }              }                      

Using Directly Uploads can sometimes issue in a file that uploads, but never attaches to a tape. Consider purging unattached uploads.

x Testing

Use fixture_file_upload to test uploading a file in an integration or controller test. Rails handles files like whatever other parameter.

                          class              SignupController              <              ActionDispatch              ::              IntegrationTest              test              "can sign upwardly"              do              mail              signup_path              ,              params:                            {              proper noun:                            "David"              ,              avatar:                            fixture_file_upload              (              "david.png"              ,              "paradigm/png"              )              }              user              =              User              .              social club              (              :created_at              ).              final              affirm              user              .              avatar              .              attached?              finish              end                      

x.1 Discarding files created during tests

ten.1.1 System tests

Organization tests clean up test data by rolling back a transaction. Because destroy is never chosen on an object, the attached files are never cleaned upward. If you lot desire to clear the files, you can practice it in an after_teardown callback. Doing it here ensures that all connections created during the test are complete and you lot won't receive an fault from Active Storage maxim information technology can't find a file.

                          class              ApplicationSystemTestCase              <              ActionDispatch              ::              SystemTestCase              # ...              def              after_teardown              super              FileUtils              .              rm_rf              (              ActiveStorage              ::              Blob              .              service              .              root              )              end              # ...              end                      

If you're using parallel tests and the DiskService, you should configure each process to use its own folder for Active Storage. This fashion, the teardown callback volition just delete files from the relevant procedure' tests.

                          class              ApplicationSystemTestCase              <              ActionDispatch              ::              SystemTestCase              # ...              parallelize_setup              exercise              |              i              |              ActiveStorage              ::              Blob              .              service              .              root              =              "              #{              ActiveStorage              ::              Hulk              .              service              .              root              }              -              #{              i              }              "              end              # ...              end                      

If your system tests verify the deletion of a model with attachments and you're using Active Job, fix your test environment to use the inline queue adapter so the purge job is executed immediately rather at an unknown time in the future.

                          # Use inline job processing to make things happen immediately              config              .              active_job              .              queue_adapter              =              :inline                      
10.one.ii Integration tests

Similarly to System Tests, files uploaded during Integration Tests volition not be automatically cleaned up. If you want to clear the files, you can do it in an teardown callback.

                          course              ActionDispatch::IntegrationTest              def              after_teardown              super              FileUtils              .              rm_rf              (              ActiveStorage              ::              Blob              .              service              .              root              )              stop              stop                      

If you're using parallel tests and the Disk service, you should configure each process to use its own folder for Active Storage. This way, the teardown callback will merely delete files from the relevant process' tests.

                          class              ActionDispatch::IntegrationTest              parallelize_setup              practice              |              i              |              ActiveStorage              ::              Blob              .              service              .              root              =              "              #{              ActiveStorage              ::              Blob              .              service              .              root              }              -              #{              i              }              "              cease              end                      

10.2 Adding attachments to fixtures

Y'all can add attachments to your existing fixtures. Showtime, you'll want to create a separate storage service:

                          # config/storage.yml              test_fixtures              :              service              :              Disk              root              :              <%= Track.root.bring together("tmp/storage_fixtures") %>                      

This tells Active Storage where to "upload" fixture files to, and so it should exist a temporary directory. By making it a different directory to your regular exam service, you can divide fixture files from files uploaded during a examination.

Next, create fixture files for the Agile Storage classes:

                          # active_storage/attachments.yml              david_avatar              :              name              :              avatar              record              :              david (User)              blob              :              david_avatar_blob                      
                          # active_storage/blobs.yml              david_avatar_blob              :              <%= ActiveStorage::FixtureSet.hulk filename              :              "              david.png"              ,              service_name              :              "              test_fixtures"              %              >                      

Then put a file in your fixtures directory (the default path is test/fixtures/files) with the corresponding filename. Encounter the ActiveStorage::FixtureSet docs for more than information.

Once everything is set, you'll be able to access attachments in your tests:

                          grade              UserTest              <              ActiveSupport              ::              TestCase              def              test_avatar              avatar              =              users              (              :david              ).              avatar              assert              avatar              .              fastened?              assert_not_nil              avatar              .              download              assert_equal              one thousand              ,              avatar              .              byte_size              terminate              end                      
10.2.1 Cleaning up fixtures

While files uploaded in tests are cleaned upward at the end of each examination, you lot only need to clean up fixture files once: when all your tests consummate.

If you're using parallel tests, call parallelize_teardown:

                          class              ActiveSupport::TestCase              # ...              parallelize_teardown              do              |              i              |              FileUtils              .              rm_rf              (              ActiveStorage              ::              Hulk              .              services              .              fetch              (              :test_fixtures              ).              root              )              end              # ...              stop                      

If you're not running parallel tests, use Minitest.after_run or the equivalent for your test framework (e.thou. after(:suite) for RSpec):

                          # test_helper.rb              Minitest              .              after_run              exercise              FileUtils              .              rm_rf              (              ActiveStorage              ::              Blob              .              services              .              fetch              (              :test_fixtures              ).              root              )              end                      

11 Implementing Back up for Other Cloud Services

If y'all need to support a deject service other than these, you will need to implement the Service. Each service extends ActiveStorage::Service by implementing the methods necessary to upload and download files to the cloud.

12 Purging Unattached Uploads

There are cases where a file is uploaded but never attached to a record. This tin can happen when using Directly Uploads. You can query for unattached records using the unattached scope. Below is an example using a custom rake job.

                          namespace              :active_storage              do              desc              "Purges unattached Active Storage blobs. Run regularly."              task              purge_unattached: :surroundings              do              ActiveStorage              ::              Blob              .              unattached              .              where              (              "active_storage_blobs.created_at <= ?"              ,              ii              .              days              .              ago              ).              find_each              (              &              :purge_later              )              end              end                      

The query generated by ActiveStorage::Blob.unattached tin can be slow and potentially disruptive on applications with larger databases.

Feedback

You lot're encouraged to help improve the quality of this guide.

Delight contribute if you run across whatever typos or factual errors. To get started, you lot tin can read our documentation contributions department.

You may also find incomplete content or stuff that is not upwardly to date. Please practise add together any missing documentation for main. Make sure to check Edge Guides first to verify if the issues are already fixed or not on the main branch. Check the Ruby on Track Guides Guidelines for manner and conventions.

If for whatever reason you spot something to set but cannot patch it yourself, please open an result.

And last but non least, whatever kind of give-and-take regarding Ruby on Rail documentation is very welcome on the rubyonrails-docs mailing list.

elderbuts1992.blogspot.com

Source: https://edgeguides.rubyonrails.org/active_storage_overview.html