简体   繁体   English

如何使文件上传保持您原来的“内容类型”到 Amazon S3?

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

TL;DR TL;博士

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?如何上传图像并维护其原始Content Type ,或者生成签名或公共 URL 以强制我的文件类型正确?

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我在 Rails 应用程序中遇到了 S3 问题(我真的在使用Minio ,它与 S3 协议兼容)

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

I create the follow method to handle uploaded file (in Rails App) and send it to Minio .我创建了以下方法来处理上传的文件(在 Rails App 中)并将其发送到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.这是我在发送到 Minio 之前上传的具有正确 Content-Type 的文件。

# 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这是我的文件,Minio 上的类型( "binary/octet-stream" )不正确

Imagens no Minio como arquivo binário

I need to send it to another service, and get the upload URL with correct Content-Type.我需要将它发送到另一个服务,并使用正确的 Content-Type 获取上传 URL。

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?那么,如何上传图像并维护其原始Content Type ,或者生成一个签名或公共 URL 来强制我的文件使用正确的类型?

You could use the put_object method on the bucket instance that accepts a hash of options, one of which is content-type ( Reference ):您可以在接受 hash 选项的存储桶实例上使用put_object方法,其中之一是内容类型( 参考):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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