Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paperclip on S3 is changing file extensions from a url

I wrote a rake task that downloads an image from wikipedia given a celebrity name, but for some reason when storing on S3 the file extension is either being dropped or changed to .txt

The file otherwise is correct.

Any ideas?

From my celeb model:

has_attached_file :pic, 
  :styles => { :medium => "300x300>", :thumb => "100x100>" },
  :default_style => :medium,
  :storage => :s3,
  :s3_credentials => "#{Rails.root}/config/s3.yml",
  :path => "/:style/:img_name.:extension"

From my rake task:

desc "Update celeb pics from wiki"
task :update_celeb_pics => [:environment] do
  include ApplicationHelper
  Celeb.all.each do |celeb|
    if !celeb.name.start_with?("(")
      puts celeb.name
      celeb.pic = open(getImage(celeb.name))
      celeb.save
    end
  end
end

the getImage method is a helper that returns a string

    require 'open-uri'
    require 'uri'

    module ApplicationHelper
      def getInfo(name)
        Nokogiri::XML(open(URI.escape("http://en.wikipedia.org/w/api.php?action=opensearch&search=#{name}&limit=1&namespace=0&format=xml")))
      end

      def nokoPage(name)
        Nokogiri::XML(open(getURL(name)))
      end

      def getImage(name)
        "http:" + nokoPage(name).css("table img")[0].attribute("src").value if !nokoPage(name).css("table img").empty?
      end

      def getDescription(name)
        getInfo(name).css("Description").text
      end

      def getURL(name)
        getInfo(name).css("Url").text
      end

      def getBday(name)
        bday = nokoPage(name).css("span.bday")
        return Date.parse(bday[0].text) if !bday.empty?
        return Date.today
      end

      def getDday(name)
        dday = nokoPage(name).css("span.dday")
        return Date.parse(dday[0].text) if !dday.empty?
      end

    end
like image 216
cbass Avatar asked Feb 19 '23 19:02

cbass


1 Answers

This is because

self.pic = open("http://something.com/bla/image.png")

is not the best solution here. Just yesterday, i got a Pull Request merged into Paperclip that lets you do this

self.pic = URI.parse(getImage(name))

This will ensure that your pic's content type matches the downloaded file, pic's filename is set to the name of the file downloaded.

The reason you get txt extension is because open returns a StringIO object which infact names the filename as "stringio.txt". Your filename is probably changed by the s3 code but the extension remains as '.txt'

I suggest you link your Gemfile to paperclip's github repo, run bundle and try again.

Cheers, Aditya

like image 150
Aditya Sanghi Avatar answered Mar 05 '23 23:03

Aditya Sanghi