Last active
November 9, 2023 14:51
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%= 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 %> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Rails.application.routes.draw do | |
post "/uploads", to: "uploads#create", as: :uploads | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.", | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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