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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With