1. 在Gemfile添加

gem 'carrierwave'
gem 'mini_magick'

执行 bundle install

2. 生成uploader

rails generate uploader UserPic 

生成文件uploaders/user_pic_uploader.rb ,修改如下

# 修改文件存储位置
def store_dir
# "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
"user_head_pic"
end # 设置默认头像
def default_url(*args)
"/assets/user_head.png"
end # 修改文件名
def filename
if original_filename
@name ||= Digest::MD5.hexdigest(current_path)
"#{@name}#{file.basename}.#{file.extension}"
end
end

3. 给user表添加用户头像字段

添加migrate文件并执行 rails db:migrate

class AddHeadPicToUsers < ActiveRecord::Migration[5.1]
def change
add_column :users,:head_pic,:string,:comment=>'头像'
end
end

4. 修改app/models/user.rb

user.rb中添加UserPicUploader

class User < ActiveRecord::Base
mount_uploader :head_pic, UserPicUploader
end

5. 保存头像

cotroller中对应的action如下

 def update_user_pic
image_info = params[:avatar]||""
if image_info.include? "data:image/png"
png = Base64.decode64(image_info['data:image/png;base64,'.length .. -1])# 将 Base64 编码的参数用 Base64 解码,得到数据的二进制表示,也就是图片本身的二进制数据
unless Dir.exists?("#{Rails.root}/public/user_head_pic")
FileUtils.mkdir_p("#{Rails.root}/public/user_head_pic")
end
file_name = "img_#{@current_user.user_no}.png"# 根据当前用户工号声明一个文件名
file_path = "#{Rails.root}/public/user_head_pic/#{file_name}" # 确定文件保存路径
File.open(file_path,'wb') do |item|# 根据文件路径创建新文件
item.write(png)# 将前面的二进制数据写到文件里
end
@current_user.head_pic = File.open(Rails.root+"public/user_head_pic/#{file_name}")
@current_user.save
flash[:notice] = "保存成功!"
else
flash[:notice] = "保存失败!"
end redirect_to :action=>:update_head
end

6. 显示头像

    <img src="<%= @user.head_pic.url%>" />

最新文章

  1. input file限制上传文件类型
  2. WPF中运行时使内容可以上下左右被鼠标拖动应该怎么做?
  3. [No00000B]MS OFFICE 2013 快捷键大全
  4. windows 下wamp环境1 配置之apache的安装
  5. Linux进程空间分布 &amp; 进程控制块 PCB
  6. 关于Split方法
  7. Html5新标签及用法
  8. windows下回车与换行符
  9. 李洪强iOS开发之-环信05_EaseUI 使用指南
  10. VS2010使用附加进程的方式调试IIS中的页面介绍
  11. Swift学习之UI开发初探
  12. pc app 桌面打包
  13. Linux Shell -- 无网不利
  14. CTO 能力模型(简化版)
  15. Codeforces 387E George and Cards
  16. webpack详细配置解析
  17. *** FATAL ERROR L250: CODE SIZE LIMIT IN RESTRICTED VERSION EXCEEDED
  18. IDEA@Data注释使用
  19. kubeadm部署Kubernetes集群
  20. C语言realloc,malloc,calloc的区别【转载】

热门文章

  1. linux定时备份MySQL数据库并删除七天前的备份文件
  2. stream操作 z
  3. February 5 2017 Week 6 Sunday
  4. 小技巧:Mac下Metasploit渗透Oracle环境的搭建
  5. whoami
  6. Vue收藏资料
  7. StringUtils工具类介绍
  8. 学会WCF之试错法——客户端调用基础
  9. IDEA+MAVEN构建一个webapp骨架项目(解决一直卡在downloading plugins for问题)
  10. Spring通过注解装配Bean