【问题标题】:How do I set content_type using StringIO to upload to S3 using PaperClip如何使用 StringIO 设置 content_type 以使用 PaperClip 上传到 S3
【发布时间】:2014-07-08 09:23:42
【问题描述】:

我正在使用以下代码将生成的 CSV 文件上传到 S3。

现在,目前整个过程正在运行,但文件被存储为“文本/纯文本”。如果我将内容类型验证更改为使用“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

如何才能将 content_type 设置为 CSV?

【问题讨论】:

    标签: ruby-on-rails-4 amazon-s3 paperclip


    【解决方案1】:

    我只找到了一种方法让它最终起作用..

    在模型中(没有这个,它不会作为文本/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!
    

    【讨论】:

    • 我只需要 s3 标头就可以让 CSV 正常工作。谢谢!
    猜你喜欢
    • 2015-10-29
    • 2010-11-26
    • 2011-05-02
    • 2023-03-29
    • 2014-10-23
    • 2011-06-29
    • 2012-03-03
    • 2014-08-11
    • 2011-09-21
    相关资源
    最近更新 更多