我使用以下代码将生成的CSV文件上传到S3。
现在,整个过程正在运行,但文件存储为&text; / text'。如果我更改内容类型验证以使用' text / csv'它因内容类型验证错误而失败。
为了简洁起见,我删除了一些代码
class Export < ActiveRecord::Base
has_attached_file :export_file
validates_attachment_content_type :export_file, :content_type => "text/plain"
public
def export_leave_requests
... csv generated in memory here ...
self.update_attributes(export_file: StringIO.new(csv_file))
self.save!
end
end
如何将此内容设置为CSV?
答案 0 :(得分:3)
我只找到了一种方法来确定这一点......
在模型中(没有它,它不作为text / csv存储在S3上):
has_attached_file :export_file,
s3_headers: lambda { |attachment|
{
'Content-Type' => 'text/csv',
'Content-Disposition' => "attachment; filename=#{attachment.filename}",
}
}
在您的导出代码中:
# read the content from a string, not a file
file = StringIO.open(csv)
# fake the class attributes
file.class.class_eval { attr_accessor :original_filename, :content_type }
file.original_filename = @export.filename
file.content_type = 'text/csv'
# Only needed if you will output contents of the file via to_s
file.class.class_eval { alias_method :to_s, :string }
@export.export_file = file
# If you don't do this it won't work - I don't know why...
@export.export_file.instance_write(:content_type, 'text/csv')
@export.save!