CodexBloom - Programming Q&A Platform

Rails 7.1: implementing S3 Direct Uploads scenarios on File Size Limit Exceeded

๐Ÿ‘€ Views: 1 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-12
ruby-on-rails activestorage aws-s3 Ruby

I've spent hours debugging this and I'm working on a project and hit a roadblock. I've been struggling with this for a few days now and could really use some help. I'm currently working on a Rails 7.1 application that uses ActiveStorage to handle file uploads directly to Amazon S3. However, I've run into an scenario where users are able to initiate a file upload, but once the file exceeds the S3 size limit (which I believe is 5GB for multipart uploads), I get a `Aws::S3::Errors::EntityTooLarge` behavior. I want to prevent users from even starting the upload if they select a file thatโ€™s too large. I've tried to check the file size on the client side before initiating the upload, but it seems that the `file.size` property is only available after the file is selected and not before. Hereโ€™s what my JavaScript looks like: ```javascript const fileInput = document.getElementById('file-upload'); fileInput.addEventListener('change', (event) => { const file = event.target.files[0]; if (file && file.size > 5 * 1024 * 1024 * 1024) { // 5GB limit alert('File is too large! Maximum size is 5GB.'); fileInput.value = ''; // Clear the input } else { // Proceed with the upload } }); ``` While this mitigates the scenario somewhat, I still notice that if a user bypasses the frontend validation (for example, by manipulating the DOM or using API requests), they can still trigger the upload. I need a robust solution to enforce this file size validation on the server side as well. Iโ€™ve considered adding a validation in my model like this: ```ruby class UserFile < ApplicationRecord validate :file_size_validation def file_size_validation if file.attached? && file.blob.byte_size > 5.gigabytes errors.add(:file, 'exceeds the maximum allowed size of 5GB') end end end ``` However, Iโ€™m uncertain if this is sufficient on its own, especially if the application is initially configured to handle uploads via S3 without checking file sizes. Could someone provide guidance on implementing a secure and efficient way to enforce file size limits both on the client and server sides? Also, are there any best practices for handling large file uploads with ActiveStorage? Any insights would be greatly appreciated. My development environment is Windows. Thanks in advance! For context: I'm using Ruby on macOS. What am I doing wrong? I'm using Ruby latest in this project. I'm open to any suggestions.