Amazon S3 Upload with Ruby

Need a quick and dirty way to upload some photos or other files via command prompt? Have Ruby?

First, install the Amazon S3 gem:

sudo gem i aws-s3

Then, edit the following to suit your needs:

#!/usr/bin/env ruby
 
require 'rubygems'
require 'aws/s3'
require 'fileutils'
 
 
ACCESS_KEY_ID = "put yours here"
SECRET_ACCESS_KEY = "put yours here" 
 
ARCHIVE_DIR = "/Users/shane/upload_archive"
UPLOAD_DIR = "/Users/shane/upload"
BUCKET = "static.digitalsanctum.com"
KEY_PREFIX = "images/"
 
class Upload
  
  def initialize
    AWS::S3::Base.establish_connection!(
      :access_key_id => ACCESS_KEY_ID,
      :secret_access_key => SECRET_ACCESS_KEY
    )
  end
  
  def put(local_file)
    base_name = File.basename(local_file)
    mime_type = mime_type(local_file)
    AWS::S3::S3Object.store(
      "#{KEY_PREFIX}#{base_name}",
      File.open(local_file),
      BUCKET,
      :content_type => mime_type,
      :access => :public_read
    )
    puts "Upload completed"
  end
  
  def mime_type(f)
    mimetype = `file --mime-type --brief #{f}`
  end
end
 
Dir.entries(UPLOAD_DIR).each do |f|
  next if (f == "." || f == "..")
  f_path = File.expand_path(File.join(UPLOAD_DIR, f))
  puts "uploading #{f_path}"
  Upload.new().put(f_path)
    
  archive_path = File.expand_path(File.join(ARCHIVE_DIR, f))
  puts "archiving #{f_path} to #{archive_path}"
  FileUtils.mv(f_path, archive_path)
end

blog comments powered by Disqus