- 浏览: 243937 次
文章分类
最新评论
-
bluky999:
中间的兼职例子很逗 哈哈哈
tornado: web.py 之 Application -
flingfox63:
学习了,详细,赞个
Ruby变量作用域的类目录结构 -
zhou6711411:
不知是版本问题还是怎么的
class A
...
Ruby变量作用域的类目录结构 -
t284299773:
你在方法中定义方法就相当于在方法中调用lambda!
Ruby变量作用域的类目录结构(补二) -
lnj888:
很是有用 不错Powerpoint converter
一个简单的link_to,ROR到底在背后做了些什么?(未完)
原文出处:http://clarkware.com/cgi/blosxom/2007/02/24
A picture might be worth a thousand words, but how many lines of code does it take to upload one to your Rails application? Sounds like a fun feature to tackle on a Friday. Let's upload some mug shots. You know, to identify the goofballs around the office.
1. Install an Image Processor
We'll need to resize the mugshots during the upload process, and we'll also want to generate thumbnails of the mugshots to use around the site.
Image processing of this kind is best handled by native code. This means you end up either building a library for your operating system or downloading a pre-built library specific to your operating system. Then you install a Ruby library (gem) that wraps the image processing library with a Ruby API. Either way, it's the least fun step of the entire process, so let's get it out of the way early.
Choose from one of the following libraries:
-
ImageScience: A light inline-Ruby library that only resizes images. (Wraps the FreeImage library.)
-
RMagick: The grand-daddy, both in terms of advanced image processing features and memory usage. (Wraps the ImageMagick library.)
-
minimagick: It's much easier on memory than RMagick because it runs the ImageMagick command in a shell.
OK, so which library should you use? Well, given that we just need to resize images (and thumbnailing is just resizing), ImageScience is a perfect fit. If you have one of the others installed, go with it. Otherwise, spend a few minutes with the short and sweet instructions for installing ImageScience and FreeImage.
2. Download the attachment_fu Plugin
To make light work of the rest of this task, we're going to use Rick Olson's attachment_fu
plugin. It's a significant rewrite of his original acts_as_attachment
plugin. That's right, this isn't Rick's first rodeo, and it's probably not his second. Seriously, I don't know of a more experienced person then Rick when it comes to uploading files into Rails applications. (And he's the king of good plugins!)
If you're using acts_as_attachment
, you might be wondering if it's time to upgrade. It's probably not one of those high-priority chores, but it's definitely something you want to consider doing soon. Rick's been working on attachment_fu
for almost a year now, and polishing it smooth in production settings. It comes with a comprehensive set of tests, as well. And as you'll see, it's more flexible than its worthy predecessor. To top it off, the public API hasn't changed. I converted an app this morning simply by renaming one declaration in a model from acts_as_attachment
to has_attachment
. Well worth the price of admission. One caveat: attachment_fu
requires Rails 1.2+.
Here's how to get it:
script/plugin install http://svn.techno-weenie.net/projects/plugins/attachment_fu/
3. Write an Upload Form
Having installed all the supporting software, it's time to write our app. Let's start with the upload form in the new.rhtml
file:
<!----> <!---->Upload A Mugshot: <!---->
<!---->
<!---->
Pretty standard form stuff, with a couple important bits. First, I'm using RESTful named routes (mugshots_paths
), but it works just as well with traditional routes. Second, the form uses the file_field
helper. That helper generates a Choose File button on the form. It's important that we call the attribute :uploaded_data
, as its the attribute name that attachment_fu
looks for when storing the image. Third, to allow the form to accept files as POST data, the form is generated with :multipart => true
. Forget either of those finer points and you're in for a long afternoon.
4. Write a Controller
The controller is oblivious to the fact that we're uploading images, so it's your typical overpaid middleman. The new
action displays the upload form and the create
action accepts the POST data.
def new @mugshot = Mugshot.new end def create @mugshot = Mugshot.new(params[:mugshot]) if @mugshot.save flash[:notice] = 'Mugshot was successfully created.' redirect_to mugshot_url(@mugshot) else render :action => :new end end
5. Write a Migration and Model
Next we need a MugShot
model (and a corresponding database table) to store the uploaded file information. Let's start with the migration file for the mugshots
database table.
class CreateMugshots < ActiveRecord::Migration def self.up create_table :mugshots do |t| t.column :parent_id, :integer t.column :content_type, :string t.column :filename, :string t.column :thumbnail, :string t.column :size, :integer t.column :width, :integer t.column :height, :integer end end def self.down drop_table :mugshots end end
How did we come up with those column names? Well, we didn't. By convention, attachment_fu
will automatically store the uploaded file information (the meta-data, if you will) in these columns. That begs the question: Where does the actual file data get stored? To answer that we need to write the MugShot
model.
class Mugshot < ActiveRecord::Base has_attachment :content_type => :image, :storage => :file_system, :max_size => 500.kilobytes, :resize_to => '320x200>', :thumbnails => { :thumb => '100x100>' } validates_as_attachment end
Here's where the attachment_fu
plugin makes you pump your fists in victory. Basically, at this point we'd rather not grovel around at the API level of whatever Ruby image library you have installed. We'd also like to program at a fairly high level and not worry about how the file information and data is stored. (We call those things implementation details when our boss is listening.)
In the has_attachment
method we tell attachment_fu
what to do with the uploaded image. The options are as follows:
:content_type
- The content types that are allowed, which defaults to all content types. Using:image
allows all standard image types.:min_size
- The minimum size allowed, which defaults to 1 byte:max_size
- The maximum size allowed, which defaults to 1 megabyte:size
- A range of allowed sizes, which overrides the:min_size
and:max_size
options:resize_to
- An array of width/height values, or a geometry string for resizing the image:thumbnails
- A set of thumbnails to generate, specified by a hash of filename suffixes and resizing options. This option can be omitted if you don't need thumbnails, and you can generate more than one thumbnail simply by adding names and sizes to the hash.:thumbnail_class
- Sets what class (model) to use for thumbnails, which defaults to the current class (MugShot, in this example). You could, for example, use a different model class with a different set of validations.:storage
- Sets where the actual image data is stored. Options include:file_system
,:db_file
, and:s3
.:processor
- Sets what image processor to use. Options includeImageScience
,Rmagick
, andMiniMagick
. By default, it will use whatever you have installed.:path_prefix
- Path to store the uploaded files, which defaults topublic/#{table_name}
by default for the filesystem. If you're using the S3 backend, it defaults to just#{table_name}
.
We don't really want folks uploading life-sized mugshots, so calling validates_as_attachment
prevents image sizes out of range from being saved. (They're still uploaded in memory, mind you.) As well, because we set an image content type, WinZip files won't be welcome, for example.
6. The Most Wanted List
OK, so now we're off to the races: select a mugshot file using the Choose File button on the form, the mugshot image is uploaded to the server, the file metadata is stored in the mugshots
database table, and the actual file data is stored in the public/mugshots
directory on the server.
Now we can show a line-up of thumbnails, with each thumbnail linked to the full-size image.
Most Wanted
<!----> <!----> <!---->
The public_filename
method gives us the public path to the full-size file or the thumbnail if passed the name of the thumbnail suffix (:thumb
, in our case). Given that we're using the filesystem as storage, this code ends up generating paths such as /mugshots/34/bad_man.png
and /mugshots/34/bad_man_thumb.png
. Those paths are relative to the $RAILS_ROOT/public
directory on our server, by default.
But Wait, There's More!
One of the big benefits of using attachment_fu
is the choice of backend storage systems. Let's say, for example, we want to store all of our mugshots on Amazon's S3 Web Service.
1. Download the AWS::S3 Library
gem install aws-s3
I wrote up a how-to on the AWS::S3 library a few weeks back, if you need a refresher. (Oh, and you thought this was a coincidence?)
2. Configure attachment_fu
First, just change the :storage
option on the MugShot
model to use :s3
. (You saw that coming.)
Then create the $RAILS_ROOT/config/amazon_s3.yml
configuration file as follows:
development: bucket_name: your_bucket_name access_key_id: your_access_key_id secret_access_key: your_secret_access_key test: bucket_name: access_key_id: secret_access_key: production: bucket_name: access_key_id: secret_access_key:
3. There Is No Step 3
Upload a new mugshot, and you'll see that the image link on the most wanted list points to your image up on the S3 server.
Enjoy!
发表评论
-
(ZZ)Ror on svn
2007-12-20 19:34 1510正好需要,zz过来,抄袭自:http://www.surui. ... -
用GetText来进行ROR的国际化和本地化
2007-11-22 15:17 1440IBM developerWorks上的一篇文章,直接贴地址, ... -
advanced act_as_solr
2007-10-31 19:40 1785原文出处:http://www.quarkruby.com/2 ... -
act_as_solr
2007-10-31 19:39 1981原文出处:http://www.quarkruby.com/2 ... -
Ambition
2007-10-31 19:36 1360原文出处:http://railsontherun.com/2 ... -
使用Inkscape提供自己的pdf服务
2007-10-31 19:34 1539原文出处:http://www.thesatya.com/bl ... -
给will_paginate加上ajax效果
2007-10-31 19:30 2151原文出处:http://railsontherun.com/2 ... -
使用rails制作图表
2007-10-31 19:21 2811原文出处:http://www.railsontherun.c ... -
如果定制attachment_fu上传文件的路径和文件名
2007-10-31 16:59 2743原文出处:http://the.railsi.st/2007/ ... -
(ZZ)Cache in Rails
2007-09-25 15:49 1512很经典的文章,留在blog里面做个收藏 Ruby on Rai ... -
(ZZ)Ruby on Rails Security Guide
2007-09-24 21:28 2675Ruby on Rails Security Gui ... -
学到三招
2007-09-24 01:54 1391第一招:用ruby-debug来调试rails程序 具体使用方 ... -
一个action的process过程
2007-09-17 00:11 2547ruby 代码 def process(req ... -
在线查看rails代码和edge rails api的网址,备份,以免忘记
2007-09-14 18:38 1325Edge Rails API: http://caboo.se ... -
总是看到returning,这到底是个什么东东,查了一下找到了源代码
2007-09-14 18:37 1379A Ruby-ized realization of the ... -
一个简单的link_to,ROR到底在背后做了些什么?(未完)
2007-09-14 18:20 3455滥用link_to会造成ror程序 ... -
学到关于include的一点儿知识
2007-08-23 18:09 1159ruby 代码 module Test ... -
在一个controller中render另外一个controller中view的时候出现问题
2007-08-21 18:27 2152我想在posts这个controller中的show.rh ... -
因为Rjs试用NetBeans
2007-06-20 09:44 1125因为昨天看Rails Recipe的时候提到了rjs,于是四处 ...
相关推荐
AT_Attachment_with_Packet_Interface_-_7_Volume_3
_storage_emulated_0_android_data_com.tencent.mm_MicroMsg_517174082dbc007f25c5bd836bdd4446_attachment_段润昌_648.wps
ATA接口的详细解读,working draft proposed American National Standard for Information Systems - ATA (ATAttachment) 78页
在MATLAB编程环境中,"H_attachment_comprose_matlab_"这个标题暗示了我们正在处理一个与图像处理或图形绘制相关的任务,特别是与生成特定形状的方位标志有关。方位标志通常用于图表中,以便清晰地指示出方向或者...
标题中的"attachment_1487958_16b_win64_2017-05-10"很可能是一个软件安装包或更新文件,尤其考虑到它与MATLAB 2016相关。这个文件名包含了几个关键信息:首先,“16b”可能表示这是MATLAB的一个版本号,可能是R2016...
当接收到数据时,接收方同样使用该生成多项式来检验数据的完整性和一致性。如果计算出的CRC与接收到的CRC匹配,那么数据很可能没有错误;如果不匹配,就表明可能在传输过程中发生了错误。 在LTE系统中,CRC的使用...
Information Technology - AT Attachment with Packet Interface - 6 (ATA/ATAPI-6)ATA_ATAPI-6标准规范,驱动开发参考文档
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd # Load the provided ...merged_data = pd.merge(attachment_2, attachment_1, on="单品编码", how="left") # Display the first few rows
very interesting matlab hev model
西门子840d数控系统说明。对方的更多更好
"attachment_finder_app" 是一个基于JavaScript开发的简单应用,主要用于帮助用户管理和标记带有附件的票证。这个应用程序的独特之处在于它允许用户自定义标签,这些标签可以方便地应用于各种票证,进而使得在报告、...
通过编写 Rectangle 类,可以了解如何定义类、如何使用成员变量和成员方法,以及如何实践面向对象编程的基本原则。 圆类 Circle 圆类 Circle 是一个基本的几何图形类,拥有一个成员变量 radius,表示圆的半径。该...
在IT行业中,"Attachment_Project:附件项目"是一个可能与文件管理和Web应用相关的项目。这个项目的描述非常简洁,只提到了“附件项目”这个名字,没有提供具体的功能或目标。不过,结合给出的标签“HTML”,我们可以...
attachment_doc是一个SquirrelMail插件,允许用户使用其浏览器查看电子邮件中的文档附件。 该插件将文档转换为html格式。 目前支持MSWord(DOC)和可移植文档格式(PDF)!
总的来说,"bugzilla_attachment_viewer" 是一个利用 JavaScript 实现的高效工具,它提升了用户在使用 Bugzilla 追踪和解决软件问题时的体验,体现了 JavaScript 在浏览器扩展开发中的强大能力。
"backlog_attachment_alert" 是一个针对Backlog平台的Chrome扩展程序,它的主要功能是在用户创建问题或发表评论时提供附件提醒服务,确保用户不会遗漏任何重要的文件上传。这个扩展程序特别适用于那些依赖Backlog...
标题中的"566223_ATTACHMENT01_filamentwinding_filament_zip_"似乎是一个文件名,其中包含了关键词"filament winding",这通常是指一种制造复合材料管状或圆柱形结构的技术。该技术涉及将连续纤维(如碳纤维或玻璃...
Attachment 1_chazhi.xlsx
标题中的“347977_ATTACHMENT01_Drillstringmodel_stick-slip_stickslip_zip_”似乎是一个特定的文档标识符,它可能指的是一个关于钻柱模型(Drillstring model)中粘滑(Stick-slip)现象的研究或技术资料的压缩包...
【标题解析】:“attachment_repo:我要分享的一些文件”这个标题表明这是一个分享的资源集合,主要可能包含各种与“attachment_repo”相关的文件。由于没有具体的上下文,我们可以理解为这是一个个人或者团队分享的...