rails异步上传文件

一个完整的例子.

环境: rails 2.0.2


1 创建一个项目

rails example
cd example

 


2 安装插件
paperclip:

svn export https://svn.thoughtbot.com/plugins/paperclip/trunk/ vendor/plugins/paperclip
 

paperclip让model具备附件功能,个人认为比attachment_fu更好用.


responds to parent:

svn export http://responds-to-parent.googlecode.com/svn/trunk vendor/plugins/responds_to_parent

 

不能用ajax来上传文件,而是用iframe来上传.iframe完成上传后需要通知母窗口,这就是responds to parent这个插件提供的功能.

3 生成基础代码

script/generate scaffold user name:string

 

先跑起来

rake db:migrate
script/server
 

OK, 访问 http://localhost:3000/users
先创建一个用户: test

4 给User增加头像功能
在user.rb中,增加

has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }

 

给users加几个字段

script/generate migration add_avatar_columns_to_user
 

修改migration文件:

class AddAvatarColumnsToUser < ActiveRecord::Migration
  def self.up
    add_column :users, :avatar_file_name, :string
    add_column :users, :avatar_content_type, :string
    add_column :users, :avatar_file_size, :integer
  end

  def self.down
    remove_column :users, :avatar_file_name
    remove_column :users, :avatar_content_type
    remove_column :users, :avatar_file_size
  end
end
 
rake db:migrate
 

修改view文件: edit.html.erb

<h1>Editing user</h1>

<%= error_messages_for :user %>

<% form_for(@user, :url => formatted_user_path(@user, 'js'), :html => {:method => :put, :id => 'avatar_form', :multipart => true, :target => 'upload_frame'}) do |f| %>
  <p>
    <b>Name</b><br />
    <%= f.text_field :name %>
  </p>
 
  <p>
    <b>avatar</b><br />
    <div id="avatar"><%= image_tag @user.avatar.url(:medium) %></div>
  </p>
  <%= f.file_field :avatar %>
  <p>
    <%= f.submit "Update" %>
  </p>
<% end %>
<iframe id='upload_frame' name="upload_frame" style="width:1px;height:1px;border:0px" src="about:blank"></iframe>

<%= link_to 'Show', @user %> |
<%= link_to 'Back', users_path %>

 


layout文件users.html.erb中增加:

<%= javascript_include_tag :defaults %>
 


users_controller.rb, 修改update方法, 增加

format.js do
  flash[:notice] = 'avatar updated'
  responds_to_parent do
    render :update do |page|
      page.replace_html :avatar, image_tag(@user.avatar.url(:medium))
      page[:avatar_form].reset
    end
  end
end
 


OK, 编辑test用户, 上传一个头像试试.

阅读更多

没有更多推荐了,返回首页