Rails4 使用 carrierwave上传图片

Rails4 使用 carrierwave上传图片

1. gem install carrierwave
2. add to Gemfile
3. bundle install

4. 修改application.rb
config.autoload_paths += %W(#{config.root}/app/uploaders)

5. rails g migration add_avatar_to_users name:string age:integer avatar:string
6. rake db:migrate
7. rails generate uploader Avatar
8. app/uploaders/avatar_uploader.rb
9. 打开模型文件,设定文件上传指定的Uploader
```ruby
class User < ActiveRecord::Base
  mount_uploader :avatar, AvatarUploader
end
```
10.注意在user_params中加上avatar, 如果这个字段是在创建model后加入的
```ruby
def user_params
  params.require(:user).permit(:name, :age, :avatar)
end
```
11. test
```ruby
u = User.new
u.avatar = File.open('/Downloads/rails_weixin/weixin.png')
u.save!
u.avatar.url
图片上传相对路径:#"/uploads/user/avatar/4/weixin.png"
u.avatar.current_path
图片上传绝对路径:#"/test_carrierwave/public/uploads/user/avatar/4/weixin.png"
u.avatar.identifier
图片名称:#"weixin.png"
```

13. 文件上传表单
```ruby
<%= form_for @user, :html => {:multipart => true} do |f| %>
  <p>
    <label>My Avatar</label>
    <%= image_tag(@user.avatar_url) if @user.avatar? %>
    <%= f.file_field :avatar %>
    <%= f.hidden_field :avatar_cache %>
  </p>
   <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :age %><br>
    <%= f.number_field :age %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
```

14. brew install imagemagick
15. 利用imagemagick进行图片处理,再avatar_uploader.rb文件中加入

```ruby
  include CarrierWave::MiniMagick
  #原图片
  process :resize_to_fit => [200, 200]
  #thumb
  version :thumb do
    process :resize_to_fill => [400,400]
  end
 
  #normal
  version :normal do
    process :resize_to_fill => [600,600]
  end
```

16. 前台现实图片,可以使用 avatar_url(:version)指定

```ruby
<%= image_tag(@user.avatar_url(:normal)) if @user.avatar? %>
```

16. 自定义文件后缀名
```ruby
  def extension_white_list
    %w(jpg jpeg gif png)
  end
```

17. 对上传的文件名进行修改
```ruby
  def filename
    Digest::SHA1.hexdigest(original_filename) if original_filename
  end
```

你可能感兴趣的:(文件上传,carrierwave)