rails ajax提交文件或图片

所要用到的插件:
1.安装responds_to_parent,下载responds_to_parent放到vendor/plugins目录下

1.view层,以下写法是为了能在controller层取到正确的file路径:
<%form_for(:attach,:url=>{:controller=>'product',:action=>'submit_attach',:format=>:js},:html=>{:multipart => true,:id=>'p_'+index.to_s,:target => 'upload_frame'}) do |f| %>
    <%=hidden_field_tag 'att_'+index.to_s,nil%>
    <%=hidden_field_tag 'index',index%>
    名称:<%=f.text_field :name,:size=>30 %><br />
    信息:<%=f.file_field :photo,:size=>16 %> <!--只是一个虚拟字段-->
    <%=f.submit '上传'%>
    <iframe id='upload_frame' name="upload_frame" style="width:1px;height:1px;border:0px" src="about:blank">
    </iframe>
<%end%>

2.model层,product_secret.rb
  #文件上传处理
  def self.filesave(upload,path)
      File.open(path, "wb") { |f| f.write(upload.read) }
  end


3. ##controller层,ajax上传附件代码
  def submit_attach
    flag=true
    index=params[:index]
    attr=params['att_'+index]
    if attr.blank?
      if params[:attach] && params[:attach][:photo] && params[:attach][:name]
          name = Time.now.strftime("%y%m%d%I%M%S") + 'size'+ params[:attach][:photo].size.to_s               ##防止文件名重复
          suffix=File.extname("#{params[:attach][:photo].original_filename}")
          name<<suffix
          directory = "public/data"      ##上传后文件的路径
          path = File.join(directory, name)
          attach=Attach.create(:name=>params[:attach][:name],:path=>path)
          ProductSecret.filesave(params[:attach][:photo],path)  ##上传文件
          error="上传成功"
      else
          error="请填写完整信息,请重新上传"
          flag=false
      end
    else
      error="附件已上传"
      flag=false
    end
    respond_to do |format|  
      if flag
        format.js do 
           responds_to_parent do    ##ajax调用
             render :update do |page|
                page.call('given_value',"pr_#{index}",attach.id)
                page.alert(error)
             end  
           end            
        end  
      else 
         format.js do 
           responds_to_parent do 
              render :update do |page|
                page.alert(error)
              end  
           end            
         end  
      end  
    end  

  end

猜你喜欢

转载自zyn-zyn.iteye.com/blog/1163143
今日推荐