0

TL;DR

How can I to upload an image and maintain its original Content Type or, generate a signed or public URL that force a correct type for my file?

I explain more:

I have a problem with S3 (I really I'm using Minio, that is compatible with S3 protocol) in Rails app with

gem 'aws-sdk-s3', '~> 1.96'

I create the follow method to handle uploaded file (in Rails App) and send it to Minio.

def upload_file(file)
  object_key = "#{Time.now.to_i}-#{file.original_filename}"
  object = @s3_bucket.object(object_key)
  object.upload_file(Pathname.new(file.path))
  
  object
end

This is my uploaded file with correct Content-Type, before it was sent to Minio.

# file
#<ActionDispatch::Http::UploadedFile:0x00007f47918ef708
 @content_type="image/jpeg",
 @headers=
  "Content-Disposition: form-data; name=\"images[]\"; filename=\"image_test.jpg\"\r\nContent-Type: image/jpeg\r\n",
 @original_filename="image_test.jpg",
 @tempfile=#<File:/tmp/RackMultipart20220120-9-gc3x7n.jpg>>

And here, is my file, with incorrect Type ("binary/octet-stream") on Minio

Imagens no Minio como arquivo binário

I need to send it to another service, and get the upload URL with correct Content-Type.

So, how can I to upload an image and maintain its original Content Type or, generate a signed or public URL that force a correct type for my file?

Holger Just
  • 52,918
  • 14
  • 115
  • 123
Luiz Carvalho
  • 1,549
  • 1
  • 23
  • 46
  • 1
    Have you tried using the put_object method? You should be able to pass additional options such as content-type. [Reference](https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/S3/Bucket.html#put_object-instance_method) –  Jan 20 '22 at 16:51
  • 1
    @sava128 you area a ANGEL MAN!!! Works fineee! I`m trying use [put](https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/S3/Object.html#put-instance_method) method from object instance... Without success, but this works gracefully. Very thanks. Please post Answer for me accept it. – Luiz Carvalho Jan 21 '22 at 14:11

1 Answers1

1

You could use the put_object method on the bucket instance that accepts a hash of options, one of which is content-type (Reference):

def upload_file(file)
  object_key = "#{Time.now.to_i}-#{file.original_filename}"
  @s3_bucket.put_object({ 
    key: object_key, 
    body: Pathname.new(file.path),
    content_type: "some/content_type" 
  })
end