ruby-on-railsaws-sdkaws-sdk-ruby

How to serve an image from S3?


I have Rails app with embedded images. What I want is to upload these images to s3 and serve them from there instead of form original source. Do I have to download the img to my server before upload it to s3?


Solution

  • Short answer: If you're scraping someone's content, then...yes, you need to pull the file down before uploading to to S3.

    Long answer: If the other site (the original source) is working with you, you can give them a Presigned URL that they can use to upload to your S3 bucket.

    From Amazon's docs: https://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjectPreSignedURLRubySDK.html

    #Uploading an object using a presigned URL for SDK for Ruby - Version 3.
    
    require 'aws-sdk-s3'
    require 'net/http'
    
    s3 = Aws::S3::Resource.new(region:'us-west-2')
    
    obj = s3.bucket('BucketName').object('KeyName')
    # Replace BucketName with the name of your bucket.
    # Replace KeyName with the name of the object you are creating or replacing.
    
    url = URI.parse(obj.presigned_url(:put))
    
    body = "Hello World!"
    # This is the contents of your object. In this case, it's a simple string.
    
    Net::HTTP.start(url.host) do |http|
      http.send_request("PUT", url.request_uri, body, {
    # This is required, or Net::HTTP will add a default unsigned content-type.
        "content-type" => "",
      })
    end
    
    puts obj.get.body.read
    # This will print out the contents of your object to the terminal window.