Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload bytes or base64 string to s3 ruby sdk

I'm trying to upload an image to s3 using the ruby aws sdk. I'm able to upload the base64 string if I don't set the content_type. If I do set the content_type to image/png the upload is just the generic image thumbnail.

obj = #<Aws::S3::Object bucket_name="mybucket", key="test">

>> params[:file]
>> "data:image/png;base64,iVB...."

obj.put(body: params[:file], content_type: 'image/png', content_encoding: 'base64')

How can I upload a Base64 string to s3? I'm also open to uploading as bytes if that's more straight forward

like image 503
user2954587 Avatar asked Jul 02 '26 10:07

user2954587


1 Answers

I managed to get it to work with put, instead of upload_file. put makes more sense, since you are trying to upload an image encoded as a base64 data uri string.

Assuming your data uri string looks like:

string = 'data:image/jpeg;base64,<base_64_string>'

The key is to decode the <base_64_string> part and send it to body in the put method:

body = Base64.decode64(string.split(',')[1])

s3 = Aws::S3::Resource.new
s3.bucket(ENV['AWS_BUCKET_NAME']).object(key).put(body: body, acl: 'public-read', content_type: 'image/jpeg', content_encoding: 'base64')

This assumes you are using the the AWS Ruby library at https://github.com/aws/aws-sdk-ruby

like image 67
Christian Fazzini Avatar answered Jul 04 '26 23:07

Christian Fazzini