typescript 113 lines · 1 tab

Image upload with preview and Rails Direct Upload

Maya Patel Jan 2026
1 tab
import { useState, useRef } from 'react'
import { DirectUpload } from '@rails/activestorage'

interface ImageUploadProps {
  onUploadComplete: (blobId: string) => void
  maxSize?: number
}

export function ImageUpload({ onUploadComplete, maxSize = 5 * 1024 * 1024 }: ImageUploadProps) {
  const [preview, setPreview] = useState<string | null>(null)
  const [uploading, setUploading] = useState(false)
  const [progress, setProgress] = useState(0)
  const [error, setError] = useState<string | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return

    setError(null)

    if (file.size > maxSize) {
      setError(`File size exceeds ${maxSize / 1024 / 1024}MB limit`)
      return
    }

    if (!file.type.startsWith('image/')) {
      setError('Please select an image file')
      return
    }

    // Show preview
    const reader = new FileReader()
    reader.onload = (e) => {
      setPreview(e.target?.result as string)
    }
    reader.readAsDataURL(file)

    // Upload to Rails
    uploadFile(file)
  }

  const uploadFile = async (file: File) => {
    setUploading(true)
    setProgress(0)

    const upload = new DirectUpload(
      file,
      '/rails/active_storage/direct_uploads',
      {
        directUploadWillStoreFileWithXHR: (xhr) => {
          xhr.upload.addEventListener('progress', (event) => {
            const percent = (event.loaded / event.total) * 100
            setProgress(Math.round(percent))
          })
        },
      }
    )

    upload.create((error, blob) => {
      setUploading(false)

      if (error) {
        setError('Upload failed. Please try again.')
        console.error('Upload error:', error)
      } else {
        onUploadComplete(blob.signed_id)
      }
    })
  }

  return (
    <div className="space-y-4">
      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        onChange={handleFileSelect}
        className="hidden"
      />

      {preview ? (
        <div className="relative">
          <img src={preview} alt="Preview" className="w-full h-64 object-cover rounded" />
          {uploading && (
            <div className="absolute inset-0 bg-black bg-opacity-50 flex items-center justify-center rounded">
              <div className="text-white">
                <div className="w-48 bg-gray-700 rounded-full h-2 mb-2">
                  <div
                    className="bg-blue-500 h-2 rounded-full transition-all"
                    style={{ width: `${progress}%` }}
                  />
                </div>
                <p className="text-sm text-center">{progress}% uploaded</p>
              </div>
            </div>
          )}
        </div>
      ) : (
        <button
          onClick={() => fileInputRef.current?.click()}
          className="w-full h-64 border-2 border-dashed border-gray-300 rounded flex flex-col items-center justify-center hover:border-blue-500 transition-colors"
        >
          <i className="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-2" />
          <p className="text-gray-600">Click to upload image</p>
          <p className="text-sm text-gray-500">Max size: {maxSize / 1024 / 1024}MB</p>
        </button>
      )}

      {error && <p className="text-red-600 text-sm">{error}</p>}
    </div>
  )
}
1 file · typescript Explain with highlit

Direct uploads to cloud storage bypass the Rails server, improving performance and reducing server load. I use ActiveStorage's Direct Upload feature to get presigned URLs from Rails, then upload files directly to S3 from the browser. The React component shows image previews using FileReader API before upload, displays upload progress, and handles errors gracefully. The DirectUpload class from @rails/activestorage manages the upload process and provides progress callbacks. After successful upload, I submit the signed blob ID to Rails to attach it to a record. This pattern works for avatars, post images, or any file uploads where immediate server processing isn't required.


Related snips

ruby
class CommentsController < ApplicationController
  before_action :set_post

  def create
    @comment = @post.comments.build(comment_params)

System test: asserting Turbo Stream responses

rails hotwire turbo
by codesnips 4 tabs
ruby
class Post < ApplicationRecord
  belongs_to :author, class_name: 'User'
  has_many :comments, dependent: :destroy

  scope :published, -> { where.not(published_at: nil).where('published_at <= ?', Time.current) }
  scope :draft, -> { where(published_at: nil) }

ActiveRecord scopes for reusable query logic

rails activerecord patterns
by Alex Kumar 1 tab
typescript
export interface RetryOptions {
  retries: number;
  baseMs: number;
  maxMs: number;
  signal?: AbortSignal;
  onRetry?: (attempt: number, delay: number, err: unknown) => void;

Exponential backoff with jitter for retries

typescript reliability retry
by codesnips 2 tabs
ruby
module Api
  module V1
    class UsersController < BaseController
      def show
        user = User.includes(:profile).find(params[:id])

ETags for conditional requests and caching

rails caching http-caching
by Alex Kumar 1 tab
ruby
class PostsController < ApplicationController
  def index
    @posts = Post.includes(:author)
                 .order(created_at: :desc)
                 .page(params[:page])
                 .per(10)

Turbo Frames: infinite scroll with lazy-loading frame

rails turbo hotwire
by codesnips 4 tabs
ruby
require "csv"

class PeopleCsvStream
  include Enumerable

  HEADERS = %w[id full_name email signed_up_at plan].freeze

Resilient CSV Export as a Streamed Response

rails performance streaming
by codesnips 3 tabs

Share this code

Here's the card — post it anywhere.

Image upload with preview and Rails Direct Upload — share card
Link copied