简体   繁体   中英

How can I to make upload of file maintain your original `Content Type` to Amazon S3?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM