31 Aug 2010
I've recently done a proof of concept using RabbitMQ, Spring AMQP and Spring Integration. This...
21 Jul 2010
In over ten years of experience building software, there are patterns and nuances that you...
13 Jul 2010
I set out to find an elegant solution to providing growl notifications for a JRuby...
05 May 2010
I've started playing around with Heroku lately and ran into an issue when I created...
30 Apr 2010
I've been meaning to investigate something that came to mind a while back and just...

Amazon S3 Upload with Ruby

Published: 25 Nov 2009

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