Pergunta

In ruby on rails project, I get a url from user and use below http request and then show the result to user. The code is show below:

problem.rb:

class Problem < ActiveRecord::Base
  def content_length

    uri = URI.parse("http://png-4.findicons.com/files/icons/1607/ruby_on_rails/256/ror_folder_256_v3.png")

    response = Net::HTTP.start(uri.host, uri.port) { |http| http.request_head(uri.path)}
    response["content-length"].to_i
  end
end

I get the image of this url and show the size and the picture of url to user:

show.html.erb:

<p>
  <strong>Image Size:</strong>
  <%= number_to_human_size(@problem.content_length) %>
</p>

<p>
  <strong>Image:</strong>
  <%= image_tag(@problem.url) %>
</p>

Now, I save the url to the database, but I want save the image of this url in database too. How can save the image into database?

Problem model, have a paperclip method that is get the image from upload the image from below code:

<div class="field">
  <%= f.label :photo %><br>
  <%= f.file_field :photo %>
</div>

Can I save the image of URL to paperclip of problems? If yes, how can I do it?

Foi útil?

Solução

As long as you are using Paperclip 3.1.4 or higher it should be as simple as setting up paperclip on your model:

class Problem
  has_attached_file :image
end

And then assigning and saving:

def attach_picture_from_url(url)
  @problem.image = URI.parse(url)
  @problem.save!
end

With Paperclip 4 there are validations in place to ensure that someone doesn't spoof the content type. If the url that you are fetching is missing the correct extension (e.g. http://exmample.com/foo returns your jpeg) then you will receive an error about the extension not matching the detected content type. If this is a use-case for you then you can do something like this:

require 'open-uri'
def attach_picture_from_url(url)
  image_handle = open url
  raise "Not an image" unless image_handle.content_type.start_with? 'image/'
  extension = image_handle.content_type.gsub 'image/', ''

  temp_file = Tempfile.new ['image', extension]
  temp_file.write image_handle.read
  temp_file.close

  @problem.image = temp_file
  @problem_image.save!
ensure
  temp_file.unlink if temp_file
end

Obviously this is more complicated, but it will ensure that the file will always have an extension that matches the content type.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top