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