ror上传图片
controller:
def update
@mobile_order_bill = MobileOrderBill.find(params[:id])
if !params[:mobile_order_bill][:invoice_sweeping_pieces].blank?
params[:mobile_order_bill][:invoice_sweeping_pieces] = upload("图片",params[:mobile_order_bill][:invoice_sweeping_pieces],params[:id])
system("cd #{Rails.root.to_s}/public/upload/invoice && rm -rf #{@mobile_order_bill.invoice_sweeping_pieces}")
end
@mobile_order_bill.update_attributes(params[:mobile_order_bill])
end
private
def upload(key,value,id)
begin
unless request.get?
if value.blank?
flash[:notice] = "请选择一个#{key}"
respond_to do |format|
format.html { redirect_to "/mobile_order_bills/#{id},all_edit/edit/" }
end
return
else
file_name = file(value)
unless file_name.blank?
flash[:notice] = "#{key}上传成功"
return file_name
else
flash[:notice] = "#{key}上传失败"
respond_to do |format|
format.html { redirect_to "/mobile_order_bills/#{id},all_edit/edit/" }
end
end
end
end
rescue => e
p e
end
end
def file(file)
if !file.original_filename.empty?
@filename= getfilename(file.original_filename)
#设置目录路径,如果目录不存在,生成新目录
FileUtils.mkdir("#{RAILS_ROOT}/public/upload/invoice") unless File.exist?("#{RAILS_ROOT}/public/upload/invoice")
#写入文件
File.open("#{RAILS_ROOT}/public/upload/invoice/#{@filename}", "wb") do |f|
f.write(file.read)
end
return @filename
end
end
#文件名
def getfilename(filename)
if !filename.nil?
Time.now.strftime("%Y_%m_%d_%H_%M_%S") + '_' +filename.split(' ').to_s
end
end
html:
<%= form_for @mobile_order_bill,:html =>{:multipart => true} do |f| %> <!-- 文件上传要开启multipart -->
<div class="row2">
<label class="item_title">上传图片:</label>
<%= f.file_field :invoice_sweeping_pieces, {:id => "bank_license"} %>
</div>
<%end%>
<%= form_tag "/agent_infos/create" ,:multipart => true do %>
<div class="row2">
<label class="item_title">上传图片:</label>
<%= file_field :agent_info,:business_license, {:id => "business_license"} %>
</div>
<%end%>
<%unless @mobile_order_bill.invoice_sweeping_pieces.blank?%>
<div class="xq_title"><p>图片展示</p></div>
<div class="row2">
<div class="item_img">
<img src="/<%= File.join('upload/invoice' , @mobile_order_bill.invoice_sweeping_pieces) %>" style=" width:300px; height:240px;" />
</div>
</div>
<%end%>

浙公网安备 33010602011771号