Rails图像上传:在Rails应用程序中使用回形针

在本系列的前两部分中,我向您展示了如何使用CarrierWave在Rails中启用图像上传。 在这一部分中,您将看到如何使用回形针进行操作。

回形针是Thoughtbot提供的Ruby宝石。 创建它是为了使文件附件变得非常容易。 在本教程中,您将看到如何与Devise一起使用Paperclip。

不用多说,让我们忙起来。

回形针需要在计算机上安装ImageMagick。 您需要此来进行图像处理。 要安装ImageMagick,请根据您使用的计算机类型使用以下任何步骤。

Mac用户:

brew install imagemagick

Ubuntu用户:

sudo apt-get install imagemagick

Rails应用程序生成

使用您的终端生成一个新的应用程序。

rails new paperclip

打开您的Gemfile并添加必要的gem:

gem 'paperclip'

gem 'devise'

完成后运行捆绑安装。

设计设置

在您的终端上,使用以下命令安装devise:

rails generate devise:install

完成后,您现在可以生成用户模型:

rails generate devise User

之后迁移数据库。

rake db:migrate

生成您的设计视图。

rails generate devise:views

使用您的文本编辑器,导航到app/views/layouts/application.html.erb并在yield块上方添加以下代码。

#app/views/layouts/application.html.erb

<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>

回形针集成

出于安全原因,我们必须允许在Devise控制器中使用参数。 感谢Devise背后的强大团队,这样做很容易。

打开app/controllers/application_controller.rb并粘贴以下代码行。

#app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.

  protect_from_forgery with: :exception
  
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation, :remember_me, :avatar, :avatar_cache) }
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:username, :password, :password_confirmation, :current_password, :avatar) }
  end
end

打开您的User模型,使其如下所示:

#app/models/user.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_attached_file :avatar, styles: { medium: "300x300", thumb: "100x100" }
  validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/
end

您需要在“用户”表中添加一个avatar列。 有一个rails命令可以从您的终端上做到这一点。

rails generate migration add_avatar_to_users

这将在db/migrate创建一个新的db/migrate 。 打开它并粘贴以下代码:

class AddAvatarToUsers < ActiveRecord::Migration
  def up
    add_attachment :users, :avatar
  end

  def down
    remove_attachment :users, :avatar
  end
end

运行您的迁移

rake db:migrate

将头像添加到设计表单

您将编辑新表单app/views/devise/registrations/new.html.erb ,并将app/views/devise/registrations/edit.html.erb表单编辑为以下内容:

#app/views/devise/registrations/new.html.erb

<h2>Sign up</h2>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { multipart: true }) do |f| %>
  <%= devise_error_messages! %>
  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true %>
  </div>

  <div class="field">
    <%= f.label :password %>
    <% if @minimum_password_length %>
    <em>(<%= @minimum_password_length %> characters minimum)</em>
    <% end %><br />
    <%= f.password_field :password, autocomplete: "off" %>
  </div>

  <div class="field">
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "off" %>
  </div>

  <div class="field">
    <%= f.file_field :avatar %>
  </div>

  <div class="actions">
    <%= f.submit "Sign up" %>
  </div>
<% end %>

<%= render "devise/shared/links" %>
#app/views/devise/registrations/edit.html.erb

<h2>Edit <%= resource_name.to_s.humanize %></h2>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
  <%= devise_error_messages! %>

  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true %>
  </div>

  <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
    <div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div>
  <% end %>

  <div class="field">
    <%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br />
    <%= f.password_field :password, autocomplete: "off" %>
  </div>

  <div class="field">
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "off" %>
  </div>

  <div class="field">
    <%= f.file_field :avatar %>
  </div>

  <div class="field">
    <%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />
    <%= f.password_field :current_password, autocomplete: "off" %>
  </div>

  <div class="actions">
    <%= f.submit "Update" %>
  </div>
<% end %>

<h3>Cancel my account</h3>

<p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %></p>

<%= link_to "Back", :back %>

启动浏览器并查看您拥有的内容。

对于标准应用程序,您可能需要检查要编辑其个人资料的用户是否已经上传了化身。 这很容易在您的注册编辑文件中实现。

打开注册编辑文件,使其如下所示:

#app/views/devise/registrations/edit.html.erb

<h2>Edit <%= resource_name.to_s.humanize %></h2>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
  <%= devise_error_messages! %>

  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true %>
  </div>

  <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
    <div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div>
  <% end %>

  <div class="field">
    <%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br />
    <%= f.password_field :password, autocomplete: "off" %>
  </div>

  <div class="field">
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "off" %>
  </div>

  <div class="field">
    <%= f.file_field :avatar %>

    <% if @user.avatar? %>
      <%= image_tag @user.avatar.url(:thumb) %>
    <% end %>
  </div>

  <div class="field">
    <%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />
    <%= f.password_field :current_password, autocomplete: "off" %>
  </div>

  <div class="actions">
    <%= f.submit "Update" %>
  </div>
<% end %>

<h3>Cancel my account</h3>

<p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %></p>

<%= link_to "Back", :back %>

你看到改变了吗?

在上面的代码中,有一条条件语句来检查用户是否已经使用行<% if @user.avatar? %>来为用户提供化身<% if @user.avatar? %> <% if @user.avatar? %> 。 如果返回true,则运行下一行,否则不运行。

安全验证

在Web应用程序中启用上传功能时,验证始终很重要。 回形针附带了一些措施来保护您的应用程序。

您可以在模型中使用以下任何验证。

class User < ActiveRecord::Base
  has_attached_file :avatar
  # Validate content type
  validates_attachment_content_type :avatar, content_type: /\Aimage/
  # Validate filename
  validates_attachment_file_name :avatar, matches: [/png\Z/, /jpe?g\Z/]
  # Explicitly do not validate
  do_not_validate_attachment_file_type :avatar
end

结论

在构建下一个Web应用程序时,您可能需要考虑Paperclip。 它有一支强大的团队来支持它。

要探索本教程未涵盖的其他功能,请查看Paperclip的GitHub页面

翻译自: https://code.tutsplus.com/tutorials/rails-image-upload-using-paperclip-in-a-rails-application--cms-25974

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值