Skip to content

Instantly share code, notes, and snippets.

@mudge
Last active November 9, 2023 14:51
Show Gist options
  • Save mudge/4ada1e311a668c4db28000c02ea599bb to your computer and use it in GitHub Desktop.
Save mudge/4ada1e311a668c4db28000c02ea599bb to your computer and use it in GitHub Desktop.
Using a custom direct upload controller with Rails Active Storage to limit file size before any data is uploaded
<%= form_with model: @post, data: { controller: 'upload', action: 'direct-upload:error@window->upload#error' } do |f| %>
<%= f.file_field(:image, data: { 'direct-upload-url' => uploads_url }) %>
<%= f.submit %>
<% end %>
Rails.application.routes.draw do
post "/uploads", to: "uploads#create", as: :uploads
end
import { Controller } from "@hotwired/stimulus";
export default class extends Controller {
error(event) {
event.preventDefault();
alert(
"Your file could not be uploaded, please try again with a file that is under 1MB in size.",
);
}
}
class UploadsController < ActiveStorage::DirectUploadsController
def create
return head :payload_too_large if blob_params.fetch(:byte_size) > 1.megabyte
super
end
private
def blob_params
params.require(:blob).permit(:byte_size)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment