当我尝试在 S3 上创建一个包含特殊字符(例如 '' “” – — é
)的文件时,文件中写入了不正确的数据,并且文件中出现了奇怪的字符。我用的是官方aws-sdk
ruby gem 由亚马逊提供。下面是示例代码:
@bucket = AppConfig.s3_bucket
@s3 = AWS::S3.new
file = @s3.buckets[@bucket].objects['amit/test']
file.write("‘test1’ “test2” test–test—test3 é-test", :acl => :public_read)
我也试过:
file.write("‘test1’ “test2” test–test—test3 é-test", :acl => :public_read, :content_type => 'text/html')
file.write("‘test1’ “test2” test–test—test3 é-test", :acl => :public_read, :content_type => 'text/plain')
file.write("‘test1’ “test2” test–test—test3 é-test", :acl => :public_read, :content_type => 'text/plain', :content_encoding => 'utf-8')
输出文件如下所示:
‘test1’ ‘test2’ test–test–test3 é-test
我已经尝试使用 aws-sdk 版本 1.11.1
和 1.65.0
。
最佳答案
这看起来你只需要指定文件的字符编码。您看到的字符串 ‘test1’ ‘test2’ test–test–test3 É-test
,如果您将其视为 Windows-1252,则它就是您的测试字符串的样子编码而不是 UTF-8。如果您在浏览器中查看(如果没有设置编码,通常默认为 1252),请尝试将浏览器使用的编码更改为 UTF-8(菜单类似于 View → Encoding
).
我不熟悉 AWS api,但看一下 the docs建议您可以使用 :content_type
选项为 write
调用指定内容类型。尝试:
file.write("‘test1’ “test2” test–test—test3 é-test", :acl => :public_read, :content_type => "text/plain; charset=utf-8")
(或者您可能需要 text/html
而不是 text/plain
。)
如果我理解了文档,这应该会导致 AWS 在检索对象时设置内容类型 header 。
这完全取决于您使用什么来获取读取 header 的对象。如果不是,您可能必须配置您的客户端以告诉它数据是 UTF-8。
关于ruby-on-rails - 将文件写入 S3 时的字符编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34945725/