使用 Paperclip 保存文件而不上传 [英] Saving files using Paperclip without upload

查看:41
本文介绍了使用 Paperclip 保存文件而不上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简短的问题.是否可以在不通过表单实际上传文件的情况下保存文件?

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

例如,假设我正在查看电子邮件中的附件,并且我想使用回形针保存它们.我该怎么做呢?我是否必须在某处手动调用 save_file(或类似的东西)?

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

任何帮助将不胜感激!

推荐答案

我有一个 rake 任务,可以将目录中的图像(客户端徽标)直接加载到 parperclip 上.您或许可以根据自己的需要进行调整.

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?

    File.open(logo_path) do |f|
      client.logo = f # just assign the logo attribute to a file
      client.save
    end #file gets closed automatically here
  end
end

问候!

这篇关于使用 Paperclip 保存文件而不上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆