views:

731

answers:

2

Hi,

I had a quick question. Is it possible to save a file without actually uploading it through a form?

For example, lets say i'm looking at attachments from emails, and i want to save them using paperclip. How do i do this? Do i manually have to call a save_file(or something similar) somewhere?

Any help would be much appreciated!

+1  A: 

The file saved in Paperclip doesn't have to be uploaded directly through a form.

I'm using Paperclip in a project to save files from URLs from webcrawler results. I'm not sure how you'd get email attachments (are they on the local file system of the server? Is your app an email app like GMail?) but as long as you can get a file stream (via something like open(URI.parse(crawl_result)) in my case...) you can attach that file to your model field that's marked has_attached_file.

This blog post about Easy Upload via URL with Paperclip helped me figure this out.

Nate
Sweet! Thanks a lot!
punit
+4  A: 

I have a rake task that loads images (client logos) from a directory directly onto parperclip. You can probably adapt it to your needs.

This is my simplified Client model:

class Client < ActiveRecord::Base
  LOGO_STYLES = {
    :original => ['1024x768>', :jpg],
    :medium   => ['256x192#', :jpg],
    :small    => ['128x96#', :jpg]
  }

  has_attached_file :logo,
    :styles => Client::LOGO_STYLES,
    :url => "/clients/logo/:id.jpg?style=:style"
  attr_protected :logo_file_name, :logo_content_type, :logo_size

Then on my rake task I do this:

# the logos are in a folder with path logos_dir
Dir.glob(File.join(logos_dir,'*')).each do |logo_path|
  if File.basename(logo_path)[0]!= '.' and !File.directory? logo_path

    client_code = File.basename(logo_path, '.*') #filename without extension
    client = Client.find_by_code(client_code) #you could use the ids, too
    raise "could not find client for client_code #{client_code}" if client.nil?

    client.logo = File.new(logo_path) #this is the most interesting line for you

    client.save
  end
end

Regards!

egarcia