whysthatso

Use Backblaze B2 As Active Storage Backend

Posted on February 27, 2025

Active storage and backblaze b2

  • for now stick with aws-sdk-s3 gem version 1.177.0 because Data Integrity Protection Headers from aws are not yet supported on b2 (https://www.backblaze.com/docs/cloud-storage-use-the-aws-sdk-for-ruby-with-backblaze-b2)
  • this is how your storage.yml backend for b2 should approximately look like:
    backblaze:
      service: S3
      access_key_id: <%= Rails.application.credentials.dig(:b2, :key_id) %>
      secret_access_key: <%= Rails.application.credentials.dig(:b2, :access_key) %>
      endpoint: https://s3.eu-central-003.backblazeb2.com
      bucket: bucket-name-<%= Rails.env %>
      region: eu-central
      request_checksum_calculation: when_required
      response_checksum_validation: when_required
    
  • these are the cors rules for direct upload to work:
[
	{
		"allowedHeaders": [
			"authorization",
			"content-type",
			"content-md5",
			"content-disposition",
			"x-bz-file-name",
			"x-bz-content-sha1"
		],
		"allowedOperations": [
			"b2_download_file_by_id",
			"b2_upload_part",
			"b2_upload_file",
			"s3_put",
			"b2_download_file_by_name",
			"s3_get",
			"s3_head"
		],
		"allowedOrigins": [
			"*" // or stricter
		],
		"corsRuleName": "downloadFromApp", // random value
		"exposeHeaders": null,
		"maxAgeSeconds": 3600
	}
]
  • form example for direct upload activated
<%= form.hidden_field :receipt, value: @bill.receipt.signed_id if @bill.receipt.attached? %>
<%= form.file_field :receipt, direct_upload: true %>

# and how to conditionally check if something is already attached
<% if @bill.receipt.attached? %>
	<%= link_to 'Download current receipt/invoice', @bill.receipt %>
<% end %>
  • this is the javascript necessary for direct upload
import * as ActiveStorage from "@rails/activestorage";

ActiveStorage.start();
  • this needed to be in the object controller for some reason i forgot
    include ActiveStorage::SetCurrent
    
  • sources
    • https://github.com/aws/aws-sdk-ruby/issues/3166
  • https://guides.rubyonrails.org/active_storage_overview.html#s3-service-amazon-s3-and-s3-compatible-apis
  • https://github.com/rails/rails/issues/50234
  • https://edgeguides.rubyonrails.org/active_storage_overview.html#direct-uploads

Hey! I'll happily receive your comments via email. Thanks for reading.

Andreas Wagner
freelance System Administrator and Ruby programmer in Tallinn, Estonia