rails 批量上传图片的功能
上图是批量上传图片并显示的效果图:
1.在cases_controller中添加 upload 批量上传的方法:
def upload(image_column) require 'upyun' bucket = Settings.carrierwave.bucket operator = Settings.carrierwave.operator password = Settings.carrierwave.password #settings 是又拍云账号的配置 upload_file = image_column upyun = Upyun::Rest.new(bucket, operator, password) new_file_name = image_column.original_filename format_str = new_file_name.split(".") new_file_name = "#{Tool.rand_file_name(15)}.#{format_str.last}" remote_file = "/image/shangyunyijia/#{new_file_name}" #远程保存图片的位置 response = upyun.put remote_file, upload_file.read "#{Settings.carrierwave.bucket_host}#{remote_file}" end
2.在cases_controller中添加 create方法:
def create photo_params = params[:photos] photo_new_params = [] #name = "shineitu[]" #params[:shineitu] 是一个数组 #循环这个数组,得到一个上传之后的图片地址数组 #然后,循环保存到photos表 if photo_params.present? photo_params['avatar'].each do |a| photo_new_params.push(upload(a)) end end anli_new_params = params[:case] ||={} if anli_new_params[:pin_mian_tu].present? anli_new_params = Tool.upload_image(anli_new_params, :pin_mian_tu) end @case = Case.new(anli_new_params) if @case.save #这个地方,既走了判断,又走了这个 .save 的操作. if photo_new_params.present? photo_new_params.each do |photo| @photo = Photo.create(:avatar => photo, :case_id => @case.id) end end redirect_to cases_path else render :new end end
3.在cases_controller中添加 update方法: (update时应该先删掉远程的图片,再create新上传的图片组)
def edit @anlis = Photo.where(:case_id => @case.id).where(:category=>"anli") end def update photo_params = params[:photos] photo_new_params = [] if photo_params.present? photo_params['avatar'].each do |a| photo_new_params.push(upload(a)) end end anli_new_params = anli_params if anli_params[:pin_mian_tu].present? anli_new_params = Tool.upload_image(anli_new_params, :pin_mian_tu) end if photo_new_params.present? @case.photos.where(:category=>"anli").destroy_all # 将原来的案例(图片)删掉 photo_new_params.each do |photo| @photo = Photo.create(:avatar=>photo, :case_id=>@case.id) end @case.update(anli_new_params) else @case.update(anli_new_params) end redirect_to cases_path end
4.edit/new 页面中添加下面代码: (循环 显示多个图片)
<div class="control-group">
<%= f.label "图片(按住Shift或Ctrl,可以选择多张, 第一张图片比例:375x286, 剩余图片比例: 350x161, 文件名不要有中文,以及特殊符号)", :id=>"image_
<div class="controls">
<%= f.file_field :avatar, :multiple => true, name:"photos[avatar][]" %>
</div>
</div>
<% if @anlis.present? %>
<% @anlis.each do |anli|%>
<%= image_tag anli.avatar, size: '100x100' if anli.avatar.present? %>
<% end %>
<% end %>