etnlmy
etnlmy

Reputation: 21

Paperclip says content type is wrong when using an external URL as attachment

I'm using Paperclip 4.2 + Rails 4.1.6 with the following model:

class Post < ActiveRecord::Base

  has_attached_file :featured_image, styles: { :medium => "300x300>", :thumb => "100x100>" }
  validates_attachment :featured_image, :content_type => { :content_type => ["image/jpeg", "image/gif", "image/png"] }


  def featured_image_from_url(url)
    self.featured_image = URI.parse(url)
  end

end

When I upload a file with the file uploader in my form, everything works fine. The attachment is set and the thumbnails are generated.

However, if I try to use a remote URL pointing to a jpeg image, like specified here, the Post cannot be saved because the attachment has the wrong content type: featured_image_content_type: "binary/octet-stream"

If I force the content type by setting it manually:

post.featured_image_content_type = "image/jpeg"
post.save

then the model is saved successfully.

Upvotes: 2

Views: 1235

Answers (2)

equivalent8
equivalent8

Reputation: 14237

here is a gem that will help you to download a url to Tempfile so this way you get around the issue with s3 sending stream mime type https://github.com/equivalent/pull_tempfile

Upvotes: 1

kierantop
kierantop

Reputation: 166

Hi I don't know whether you found a workaround yet. I have used the following code (amended for your example) to stop Paperclip (4.2.1) raising an exception when a webserver returns an incorrect content-type:

def featured_image_from_url(url)
  self.featured_image = URI.parse(url)
  # deal with the case where the webserver
  # returns an incorrect content-type
  adapter = Paperclip.io_adapters.for(featured_image)
  self.featured_image_content_type = Paperclip::ContentTypeDetector.new(adapter.path).detect
end

There may be a neater or more correct way!

Upvotes: 2

Related Questions