Search code examples
ruby-on-railsamazon-s3carrierwavejquery-file-upload

"undefined method `file' for #<String:0x007ffaf0049a28>" in Rails?


I'm getting this error

undefined method `file' for #<String:0x007ffaf0049a28>

when trying to display the content_type (ex. image/jpg) of a file. I'm using Carrierwave + Jquery File (both heavily modified to work together the way I want) + Amazon s3 (click this to see what I'm doing). It was working before with just carrierwave & amazon s3 but when I added the jquery file upload & direct s3, it's just not working any longer.

Can someone please help me out here? Here's what I'm doing:

<%= @post.attach.file.content_type %>

Thank you ahead of time & please let me know if you need more code/info

@post.attach.inspect
# https://sharebook.s3.amazonaws.com/uploads/d4247713-6459-484f-9b8b-f0b7b689e8d9/picture.jpg

@post.inspect
# #<Post id: 1, name: "post title", attach: "https://domain.s3.amazonaws.com/uploads/d4247713...", created_at: "2013-05-29 17:30:46", updated_at: "2013-05-29 17:30:46">

More info: I'm using storage :fog. In my carrierwave uploader, I have included

CarrierWave::MimeTypes process :set_content_type

Solution

  • Do you store the content type, i.e. with the carrierwave-meta gem?
    Files don't have mime types, parts of multi part form have.
    Carrierwave can get the mime_type of a file when it is uploaded.
    So it's common to store it as meta data with the uploaded file.

    Once you have carrierwave-meta installed and added the fields for the meta data (see github page of carrierwave-meta ), you can

      process :set_content_type
      process :store_meta
    

    in your uploader and access the content_type with

    @post.attach.content_type
    

    You asked for a way to look up mime_types by extension.

    The file extension is just a hint mainly used by Win. Unix relies on file content (magic chars etc), MacOS in meta data stored in the resource fork. Said this, there is a method to look up:

    Mime::Type.lookup_by_extension 
    

    see Rails API

    So the mime_type of a file stored in S3:

    mime_type = Mime::Type.lookup_by_extension(File.extension(@post.attach.inspect))