Ruby Library to Upload to Google Drive

Agile Storage Overview

This guide covers how to adhere files to your Active Record models.

After reading this guide, you lot volition know:

  • How to attach i or many files to a tape.
  • How to delete an fastened file.
  • How to link to an attached file.
  • How to use variants to transform images.
  • How to generate an image representation of a non-paradigm file, such equally a PDF or a video.
  • How to send file uploads directly from browsers to a storage service, bypassing your awarding servers.
  • How to make clean up files stored during testing.
  • How to implement back up for additional storage services.

Chapters

  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 fashion
    • Proxy mode
    • Authenticated Controllers
  6. Downloading Files
  7. Analyzing Files
  8. Displaying Images, Videos, and PDFs
    • Lazy vs Firsthand Loading
    • Transforming Images
    • Previewing Files
  9. Direct Uploads
    • Usage
    • Cross-Origin Resource Sharing (CORS) configuration
    • Direct upload JavaScript events
    • Example
    • Integrating with Libraries or Frameworks
  10. Testing
    • Discarding files created during tests
    • Adding attachments to fixtures
  11. Implementing Support for Other Deject Services
  12. Purging Unattached Uploads

1 What is Agile Storage?

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

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

ane.1 Requirements

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

  • libvips v8.6+ or ImageMagick for paradigm analysis and transformations
  • ffmpeg v3.four+ for video previews and ffprobe for video/sound analysis
  • poppler or muPDF for PDF previews

Paradigm assay and transformations besides crave the image_processing gem. Uncomment it in your Gemfile, or add information technology if necessary:

                          jewel              "image_processing"              ,              ">= 1.2"                      

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

Before you lot install and use third-party software, make certain yous understand the licensing implications of doing so. MuPDF, in particular, is licensed under AGPL and requires a commercial license for some use.

2 Setup

Active Storage uses 3 tables in your application's database named active_storage_blobs, active_storage_variant_records and active_storage_attachments. Afterwards creating a new application (or upgrading your application to Rails 5.two), run bin/runway 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 join table that stores your model's class name. If your model's class name changes, you volition need to run a migration on this table to update the underlying record_type to your model'south new class proper noun.

If you are using UUIDs instead of integers equally the chief key on your models you will demand to change the cavalcade blazon of active_storage_attachments.record_id and active_storage_variant_records.id in the generated migration appropriately.

Declare Active Storage services in config/storage.yml. For each service your application uses, provide a name and the requisite configuration. The example below declares three services named local, exam, and amazon:

                          local              :              service              :              Disk              root              :              <%= Rails.root.join("storage") %>              exam              :              service              :              Deejay              root              :              <%= Rails.root.bring together("tmp/storage") %>              amazon              :              service              :              S3              access_key_id              :              "              "              secret_access_key              :              "              "              saucepan              :              "              "              region              :              "              "              # east.g. 'us-east-i'                      

Tell Active Storage which service to utilize past setting Rails.awarding.config.active_storage.service. Because each environment will probable use a different service, information technology is recommended to do this on a per-environment basis. To use the disk service from the previous case in the development surroundings, you would add together the following to config/environments/evolution.rb:

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

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

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

To employ the exam service when testing, you add the following to config/environments/test.rb:

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

Continue reading for more data on the congenital-in service adapters (due east.g. Disk and S3) and the configuration they require.

Configuration files that are environment-specific volition take precedence: in production, for case, the config/storage/production.yml file (if real) will take precedence over the config/storage.yml file.

Information technology is recommended to use Rails.env in the saucepan names to further reduce the run a risk of accidentally destroying product data.

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

2.1 Disk Service

Declare a Disk service in config/storage.yml:

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

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

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

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

Optionally provide customer and upload options:

                          amazon              :              service              :              S3              access_key_id              :              "              "              secret_access_key              :              "              "              region              :              "              "              saucepan              :              "              "              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 sure failure scenarios, the default AWS customer configuration may cause connections to exist held for upwards to several minutes and lead to asking queuing.

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

                          precious stone              "aws-sdk-s3"              ,              require:                            false                      

The core features of Active Storage require the post-obit permissions: s3:ListBucket, s3:PutObject, s3:GetObject, and s3:DeleteObject. Public access additionally requires s3:PutObjectAcl. If you lot have additional upload options configured such as setting ACLs then additional permissions may be required.

If you want to use environment variables, standard SDK configuration files, profiles, IAM case profiles or task roles, you tin can omit the access_key_id, secret_access_key, and region keys in the example 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 can check them in AWS S3 Client 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 the azure-storage-blob precious stone to your Gemfile:

                          jewel              "azure-storage-blob"              ,              crave:                            false                      

two.4 Google Deject Storage Service

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

                          google              :              service              :              GCS              credentials              :              <%= Rails.root.join("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              :              <%= Rails.application.credentials.dig(:gcs, :private_key_id) %>              private_key              :              <%= Rails.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              :              "              "              projection              :              "              "              bucket              :              "              "                      

Optionally provide a Enshroud-Control metadata to assail uploaded assets:

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

Optionally use IAM instead of the credentials when signing URLs. This is useful if yous are authenticating your GKE applications with Workload Identity, run across this Google Deject weblog post for more than information.

                          google              :              service              :              GCS              ...              iam              :              true                      

Optionally use a specific GSA when signing URLs. When using IAM, the metadata server will be contacted to get the GSA electronic mail, just this metadata server is not always present (e.m. local tests) and you lot may wish to utilise a non-default GSA.

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

Add together the google-cloud-storage precious stone to your Gemfile:

                          gem              "google-cloud-storage"              ,              "~> 1.xi"              ,              require:                            false                      

ii.five Mirror Service

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

A mirror service is intended to be used temporarily during a migration between services in production. You can start mirroring to a new service, copy pre-existing files from the sometime service to the new, then get all-in on the new service.

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

Define each of the services y'all'd like 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              :              "              "              saucepan              :              "              "              s3_east_coast              :              service              :              S3              access_key_id              :              "              "              secret_access_key              :              "              "              region              :              "              "              bucket              :              "              "              production              :              service              :              Mirror              primary              :              s3_east_coast              mirrors              :              -              s3_west_coast                      

Although all secondary services receive uploads, downloads are ever handled by the chief service.

Mirror services are uniform with direct uploads. New files are direct uploaded to the primary service. When a direct-uploaded file is attached to a tape, a background chore is enqueued to copy it to the secondary services.

2.half-dozen Public access

By default, Active Storage assumes individual admission to services. This means generating signed, unmarried-use URLs for blobs. If you'd rather make blobs publicly accessible, specify public: truthful in your app's config/storage.yml:

                          gcs              :              &gcs              service              :              GCS              project              :              "              "              private_gcs              :              <<              :              *gcs              credentials              :              <%= Rail.root.join("path/to/private_keyfile.json") %>              saucepan              :              "              "              public_gcs              :              <<              :              *gcs              credentials              :              <%= Runway.root.bring together("path/to/public_keyfile.json") %>              bucket              :              "              "              public              :              true                      

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

When converting an existing application to employ public: true, make certain to update every individual file in the saucepan to be publicly-readable earlier switching over.

3 Attaching Files to Records

3.i has_one_attached

The has_one_attached macro sets up a one-to-i mapping betwixt records and files. Each record can have ane file attached to it.

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

                          class              User              <              ApplicationRecord              has_one_attached              :avatar              stop                      

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

                          bin              /              rails              generate              model              User              avatar              :attachment                      

You 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              ,              :countersign              ,              :avatar              )              end              stop                      

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

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

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

In some cases you might want to override a default service for a specific attachment. You can configure specific services per attachment using the service option:

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

Yous can configure specific variants per zipper by calling the variant method on yielded attachable object:

                          class              User              <              ApplicationRecord              has_one_attached              :avatar              practise              |              attachable              |              attachable              .              variant              :pollex              ,              resize_to_limit:                            [              100              ,              100              ]              finish              end                      

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

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

3.2 has_many_attached

The has_many_attached macro sets up a i-to-many relationship between records and files. Each tape tin accept many files attached to information technology.

For instance, suppose your awarding has a Bulletin model. If you want each message to accept many images, define the Message model as follows:

                          class              Message              <              ApplicationRecord              has_many_attached              :images              end                      

or if y'all are using Track 6.0+, you lot can run a model generator control like this:

                          bin              /              rails              generate              model              Message              images              :attachments                      

You can create a bulletin with images:

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

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

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

Phone call images.attached? to determine whether a particular bulletin has whatsoever images:

                          @message              .              images              .              fastened?                      

Overriding the default service is done the same mode every bit has_one_attached, by using the service option:

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

Configuring specific variants is done the same style every bit has_one_attached, past calling the variant method on the yielded attachable object:

                          class              Message              <              ApplicationRecord              has_many_attached              :images              do              |              attachable              |              attachable              .              variant              :thumb              ,              resize_to_limit:                            [              100              ,              100              ]              finish              end                      

three.3 Attaching File/IO Objects

Sometimes y'all need to attach a file that doesn't arrive via an HTTP asking. For case, you lot may want to attach a file you generated on disk or downloaded from a user-submitted URL. You may also desire to attach a fixture file in a model test. To do that, provide a Hash containing at to the lowest degree an open IO object and a filename:

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

When possible, provide a content type equally well. Agile Storage attempts to determine a file's content type from its information. It falls dorsum to the content blazon you lot provide if information technology tin't practice that.

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

You tin can bypass the content type inference from the data by passing in identify: false along with the content_type.

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

If you don't provide a content type and Active Storage can't make up one's mind the file'southward content type automatically, it defaults to awarding/octet-stream.

iv Removing Files

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

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

5 Serving Files

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

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

five.1 Redirect mode

To generate a permanent URL for a blob, you can laissez passer 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              )              # => /runway/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 example, mirroring attachments in different 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 y'all to fix the disposition.

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

To prevent XSS attacks, Active Storage forces the Content-Disposition header to "attachment" for some kind of files. To change this behaviour encounter the available configuration options in Configuring Rail Applications.

If you need to create a link from outside of controller/view context (Background jobs, Cronjobs, etc.), yous can access the rails_blob_path similar this:

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

v.2 Proxy manner

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

You can configure Agile Storage to use proxying by default:

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

Or if you want to explicitly proxy specific attachments in that location are URL helpers you tin apply in the class of rails_storage_proxy_path and rails_storage_proxy_url.

                          <%=              image_tag              rails_storage_proxy_path              (              @user              .              avatar              )              %>                      
five.2.i Putting a CDN in front end of Active Storage

Additionally, in gild to employ a CDN for Agile Storage attachments, you will need to generate URLs with proxy mode so that they are served by your app and the CDN will cache the attachment 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 likewise brand sure that the generated URLs use the CDN host instead of your app host. At that place are multiple ways to achieve this, just in general it involves tweaking your config/routes.rb file so that you can generate the proper URLs for the attachments and their variations. Every bit an example, yous could add 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              .              blob              .              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'              ])              )              end              end                      

and then generate routes similar this:

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

5.3 Authenticated Controllers

All Active Storage controllers are publicly accessible past default. The generated URLs use a evidently signed_id, making them hard to guess simply permanent. Anyone that knows the blob URL volition exist able to admission it, even if a before_action in your ApplicationController would otherwise require a login. If your files require a college level of protection, you lot tin can implement your own authenticated controllers, based on the ActiveStorage::Blobs::RedirectController, ActiveStorage::Blobs::ProxyController, ActiveStorage::Representations::RedirectController and ActiveStorage::Representations::ProxyController

To only permit an account to admission their own logo y'all could do the following:

                          # config/routes.rb              resource              :business relationship              exercise              resource              :logo              finish                      
                          # app/controllers/logos_controller.rb              class              LogosController              <              ApplicationController              # Through ApplicationController:              # include Cosign, SetCurrentAccount              def              show              redirect_to              Current              .              account              .              logo              .              url              end              cease                      
                          <%=              image_tag              account_logo_path              %>                      

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

                          config              .              active_storage              .              draw_routes              =              false                      

to prevent files being accessed with the publicly accessible URLs.

six Downloading Files

Sometimes you need to process a hulk later on information technology's uploaded—for example, to convert it to a different format. Employ the attachment'southward download method to read a hulk'south binary data into memory:

                          binary              =              user              .              avatar              .              download                      

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

                          bulletin              .              video              .              open              exercise              |              file              |              system              '/path/to/virus/scanner'              ,              file              .              path              # ...              end                      

It's important to know that the file is not yet available in the after_create callback merely in the after_create_commit just.

7 Analyzing Files

Active Storage analyzes files in one case they've been uploaded by queuing a job in Active Task. Analyzed files will store additional information in the metadata hash, including analyzed: true. Y'all can check whether a blob has been analyzed by calling analyzed? on information technology.

Image assay provides width and peak attributes. Video analysis provides these, too every bit duration, angle, display_aspect_ratio, and video and audio booleans to indicate the presence of those channels. Audio analysis provides duration and bit_rate attributes.

8 Displaying Images, Videos, and PDFs

Active Storage supports representing a variety of files. You tin can telephone call representation on an zipper to brandish an prototype variant, or a preview of a video or PDF. Before calling representation, check if the zipper tin be represented by calling representable?. Some file formats tin't be previewed by Active Storage out of the box (e.grand. Word documents); if representable? returns fake you may want to link to the file instead.

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

Internally, representation calls variant for images, and preview for previewable files. Y'all can also call these methods directly.

8.ane Lazy vs Immediate Loading

By default, Agile Storage volition 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 brand a request to that controller, which will render a 302 redirect to the file on the remote service (or in proxy mode, render the file contents). Loading the file lazily allows features like single employ URLs to work without slowing down your initial page loads.

This works fine for most cases.

If you lot desire to generate URLs for images immediately, you lot tin call .processed.url:

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

The Active Storage variant tracker improves performance of this, by storing a record in the database if the requested representation has been candy earlier. Thus, the above code will only make an API telephone call to the remote service (e.1000. S3) once, and once a variant is stored, will utilise that. The variant tracker runs automatically, merely tin be disabled through config.active_storage.track_variants.

If you're rendering lots of images on a page, the to a higher place case could result in N+1 queries loading all the variant records. To avoid these Due north+1 queries, employ the named scopes on ActiveStorage::Attachment.

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

eight.2 Transforming Images

Transforming images allows you to brandish the image at your choice of dimensions. To create a variation of an image, call variant on the attachment. You can laissez passer any transformation supported by the variant processor to the method. When the browser hits the variant URL, Agile 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, Agile Storage will automatically apply transformations depending on the paradigm'due south format:

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

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

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

The two processors are not fully uniform, so when migrating an existing application betwixt MiniMagick and Vips, some changes have to be made if using options that are format specific:

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

8.three Previewing Files

Some non-image files can be previewed: that is, they can be presented equally images. For example, a video file can exist previewed by extracting its offset frame. Out of the box, Active Storage supports previewing videos and PDF documents. To create a link to a lazily-generated preview, use the attachment's preview method:

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

To add together support for some other format, add your own previewer. Run into the ActiveStorage::Preview documentation for more than data.

nine Direct Uploads

Active Storage, with its included JavaScript library, supports uploading direct from the client to the cloud.

9.ane Usage

  1. Include activestorage.js in your application'south JavaScript parcel.

    Using the asset pipeline:

                                      //= crave activestorage                              

    Using the npm package:

                                      import                  *                  as                  ActiveStorage                  from                  "                  @rails/activestorage                  "                  ActiveStorage                  .                  kickoff                  ()                              
  2. Add direct_upload: truthful to your file field:

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

    Or, if you aren't using a FormBuilder, add the information attribute direct:

                                      <input                  blazon=                  file                  data-straight-upload-url=                  "                  <%=                  rails_direct_uploads_url                  %>                  "                  />                              
  3. Configure CORS on 3rd-political party storage services to permit direct upload requests.

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

9.2 Cross-Origin Resource Sharing (CORS) configuration

To make direct uploads to a third-party service work, yous'll demand to configure the service to allow cross-origin requests from your app. Consult the CORS documentation for your service:

  • S3
  • Google Cloud Storage
  • Azure Storage

Have care to let:

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

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

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

9.3 Direct upload JavaScript events

Event name Effect target Event data (event.detail) Description
direct-uploads:start <form> None A form containing files for direct upload fields was submitted.
direct-upload:initialize <input> {id, file} Dispatched for every file subsequently class submission.
direct-upload:start <input> {id, file} A direct upload is starting.
directly-upload:before-blob-request <input> {id, file, xhr} Before making a asking to your awarding for direct upload metadata.
direct-upload:before-storage-request <input> {id, file, xhr} Before making a asking to shop a file.
direct-upload:progress <input> {id, file, progress} As requests to store files progress.
direct-upload:error <input> {id, file, error} An error occurred. An alert will brandish unless this event is canceled.
directly-upload:terminate <input> {id, file} A straight upload has ended.
direct-uploads:finish <form> None All straight uploads have ended.

9.4 Example

You can utilize these events to show the progress of an upload.

direct-uploads

To testify the uploaded files in a grade:

                          // direct_uploads.js              addEventListener              (              "              direct-upload:initialize              "              ,              result              =>              {              const              {              target              ,              detail              }              =              effect              const              {              id              ,              file              }              =              detail              target              .              insertAdjacentHTML              (              "              beforebegin              "              ,              `     <div id="direct-upload-              ${              id              }              " class="direct-upload direct-upload--awaiting">       <div id="directly-upload-progress-              ${              id              }              " class="direct-upload__progress" style="width: 0%"></div>       <bridge class="straight-upload__filename"></span>     </div>   `              )              target              .              previousElementSibling              .              querySelector              (              `.direct-upload__filename`              ).              textContent              =              file              .              name              })              addEventListener              (              "              direct-upload:start              "              ,              event              =>              {              const              {              id              }              =              consequence              .              detail              const              element              =              document              .              getElementById              (              `directly-upload-              ${              id              }              `              )              element              .              classList              .              remove              (              "              direct-upload--awaiting              "              )              })              addEventListener              (              "              direct-upload:progress              "              ,              event              =>              {              const              {              id              ,              progress              }              =              event              .              detail              const              progressElement              =              document              .              getElementById              (              `directly-upload-progress-              ${              id              }              `              )              progressElement              .              style              .              width              =              `              ${              progress              }              %`              })              addEventListener              (              "              direct-upload:error              "              ,              effect              =>              {              issue              .              preventDefault              ()              const              {              id              ,              error              }              =              event              .              detail              const              chemical element              =              document              .              getElementById              (              `direct-upload-              ${              id              }              `              )              chemical element              .              classList              .              add              (              "              direct-upload--error              "              )              element              .              setAttribute              (              "              title              "              ,              error              )              })              addEventListener              (              "              directly-upload:end              "              ,              event              =>              {              const              {              id              }              =              outcome              .              particular              const              element              =              document              .              getElementById              (              `straight-upload-              ${              id              }              `              )              element              .              classList              .              add together              (              "              direct-upload--complete              "              )              })                      

Add styles:

                          /* direct_uploads.css */              .direct-upload              {              display              :              inline-cake              ;              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              ;              }              .straight-upload--pending              {              opacity              :              0.6              ;              }              .direct-upload__progress              {              position              :              accented              ;              elevation              :              0              ;              left              :              0              ;              bottom              :              0              ;              opacity              :              0.2              ;              background              :              #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--mistake              {              edge-color              :              red              ;              }              input              [              type              =              file              ][              information-direct-upload-url              ][              disabled              ]              {              brandish              :              none              ;              }                      

nine.5 Integrating with Libraries or Frameworks

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

                          import              {              DirectUpload              }              from              "              @rails/activestorage              "              const              input              =              certificate              .              querySelector              (              '              input[type=file]              '              )              // Demark to file drop - utilise the ondrop on a parent element or utilize a              //  library like Dropzone              const              onDrop              =              (              result              )              =>              {              result              .              preventDefault              ()              const              files              =              result              .              dataTransfer              .              files              ;              Assortment              .              from              (              files              ).              forEach              (              file              =>              uploadFile              (              file              ))              }              // Bind to normal file pick              input              .              addEventListener              (              '              modify              '              ,              (              event              )              =>              {              Array              .              from              (              input              .              files              ).              forEach              (              file              =>              uploadFile              (              file              ))              // you might articulate the selected files from the input              input              .              value              =              zip              })              const              uploadFile              =              (              file              )              =>              {              // your form needs the file_field direct_upload: true, which              //  provides information-directly-upload-url              const              url              =              input              .              dataset              .              directUploadUrl              const              upload              =              new              DirectUpload              (              file              ,              url              )              upload              .              create              ((              fault              ,              hulk              )              =>              {              if              (              error              )              {              // Handle the error              }              else              {              // Add an appropriately-named hidden input to the form with a              //  value of blob.signed_id so that the blob ids will be              //  transmitted in the normal upload flow              const              hiddenField              =              document              .              createElement              (              '              input              '              )              hiddenField              .              setAttribute              (              "              blazon              "              ,              "              hidden              "              );              hiddenField              .              setAttribute              (              "              value              "              ,              hulk              .              signed_id              );              hiddenField              .              name              =              input              .              proper noun              document              .              querySelector              (              '              class              '              ).              appendChild              (              hiddenField              )              }              })              }                      

If yous demand to rails the progress of the file upload, you can pass a third parameter to the DirectUpload constructor. During the upload, DirectUpload will call the object'due south directUploadWillStoreFileWithXHR method. You tin can so bind your own progress handler on the XHR.

                          import              {              DirectUpload              }              from              "              @rails/activestorage              "              form              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 subconscious input to the form              // with a value of blob.signed_id              }              })              }              directUploadWillStoreFileWithXHR              (              asking              )              {              request              .              upload              .              addEventListener              (              "              progress              "              ,              effect              =>              this              .              directUploadDidProgress              (              consequence              ))              }              directUploadDidProgress              (              issue              )              {              // Use effect.loaded and issue.full to update the progress bar              }              }                      

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

10 Testing

Employ fixture_file_upload to exam uploading a file in an integration or controller exam. Rails handles files similar any other parameter.

                          class              SignupController              <              ActionDispatch              ::              IntegrationTest              test              "can sign up"              do              mail service              signup_path              ,              params:                            {              proper noun:                            "David"              ,              avatar:                            fixture_file_upload              (              "david.png"              ,              "epitome/png"              )              }              user              =              User              .              order              (              :created_at              ).              last              assert              user              .              avatar              .              fastened?              end              end                      

10.1 Discarding files created during tests

10.1.1 System tests

System 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 desire to articulate the files, you can do it in an after_teardown callback. Doing information technology here ensures that all connections created during the test are consummate and y'all won't receive an error from Active Storage maxim it tin't find a file.

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

If you're using parallel tests and the DiskService, yous should configure each process to use its own binder for Active Storage. This way, the teardown callback will only delete files from the relevant process' tests.

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

If your system tests verify the deletion of a model with attachments and you lot're using Active Task, gear up your exam environment to utilize the inline queue adapter so the purge job is executed immediately rather at an unknown time in the future.

                          # Utilize inline chore processing to make things happen immediately              config              .              active_job              .              queue_adapter              =              :inline                      
10.1.2 Integration tests

Similarly to Organization Tests, files uploaded during Integration Tests volition non exist automatically cleaned upward. If you want to clear the files, you tin do it in an teardown callback.

                          class              ActionDispatch::IntegrationTest              def              after_teardown              super              FileUtils              .              rm_rf              (              ActiveStorage              ::              Hulk              .              service              .              root              )              end              cease                      

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

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

10.2 Adding attachments to fixtures

You can add attachments to your existing fixtures. Beginning, yous'll desire to create a split storage service:

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

This tells Active Storage where to "upload" fixture files to, and so information technology should exist a temporary directory. By making information technology a different directory to your regular test service, y'all can separate fixture files from files uploaded during a test.

Next, create fixture files for the Active Storage classes:

                          # active_storage/attachments.yml              david_avatar              :              name              :              avatar              tape              :              david (User)              blob              :              david_avatar_blob                      
                          # active_storage/blobs.yml              david_avatar_blob              :              <%= ActiveStorage::FixtureSet.blob 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. Run across the ActiveStorage::FixtureSet docs for more information.

Once everything is prepare upward, yous'll be able to access attachments in your tests:

                          class              UserTest              <              ActiveSupport              ::              TestCase              def              test_avatar              avatar              =              users              (              :david              ).              avatar              assert              avatar              .              attached?              assert_not_nil              avatar              .              download              assert_equal              thousand              ,              avatar              .              byte_size              end              finish                      
10.two.ane Cleaning up fixtures

While files uploaded in tests are cleaned upwardly at the end of each test, yous but demand to clean up fixture files in one case: when all your tests consummate.

If you lot're using parallel tests, call parallelize_teardown:

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

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

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

11 Implementing Support for Other Cloud Services

If you need to back up a cloud service other than these, you volition 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 only never attached to a record. This can happen when using Direct Uploads. You tin query for unattached records using the unattached scope. Below is an instance using a custom rake chore.

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

The query generated by ActiveStorage::Blob.unattached can exist dull and potentially disruptive on applications with larger databases.

Feedback

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

Please contribute if you run into any typos or factual errors. To go started, yous tin read our documentation contributions section.

You may also find incomplete content or stuff that is not upwardly to date. Please do add any missing documentation for primary. Make sure to cheque Border Guides starting time to verify if the issues are already fixed or not on the principal branch. Check the Scarlet on Rails Guides Guidelines for mode and conventions.

If for any reason you spot something to fix but cannot patch information technology yourself, please open an issue.

And final only not least, any kind of discussion regarding Reddish on Rails documentation is very welcome on the rubyonrails-docs mailing listing.

saldanashink1999.blogspot.com

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

0 Response to "Ruby Library to Upload to Google Drive"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel