Carrierwave S3通过remote_file_url设置content_type失败求助
CarrierWave 使用 remote_file_url 保存PDF时Content-Type异常问题
问题现象
- 通过
remote_file_url保存PDF文件时,S3中存储的文件Content-Type被设置为binary/octet-stream,导致浏览器无法预览,直接触发下载 - 手动给参数添加
content_type: 'application/pdf'和target_filetype: 'application/pdf'后,数据库中attachment.content_type显示为正确的application/pdf,但S3里的文件Content-Type仍为binary/octet-stream,且attachment.file.content_type返回值还是binary/octet-stream - 将该PDF下载后通过前端上传,Content-Type会被自动设置为
application/pdf,预览功能恢复正常
相关代码与环境
保存文件的核心代码
params = { filetype: 'draft', original_filename: @filename } params.merge!(remote_file_url: file) params.merge!(content_type: 'application/pdf') if type == :pdf params.merge!(target_filetype: 'application/pdf') if type == :pdf attachment = order.attachments.new(params) attachment.save!
使用的Gem版本
gem 'aws-sdk-s3', '~> 1.119' gem 'carrierwave', '~> 2.2', '>= 2.2.3' gem 'copy_carrierwave_file', '~> 1.3' gem 'file_validators', '~> 3.0' gem 'fog-aws', '~> 3.17'
控制台对象检查结果
[9] pry(#<xxx::SaveFile>)> attachment.file.content_type => "binary/octet-stream" [10] pry(#<xxx::SaveFile>)> attachment.content_type => "application/pdf"
已尝试的无效方案
- 排查前端上传控制器与上传器,未发现手动修改Content-Type的代码逻辑
- 在
mime_types.rb中添加Mime::Type.register 'application/pdf', :pdf并重启服务,无效果 - 参考旧版本CarrierWave的Content-Type设置方案,但官方文档说明0.11版本后无需手动配置
补充说明
目前临时解决办法是让生成PDF的服务方在返回文件时设置正确的Content-Type,但希望找到自身代码层面的解决路径,确认该问题是否为CarrierWave或相关Gem的Bug。
内容的提问来源于stack exchange,提问作者Chaos
相关产品推荐
相关产品推荐

