2011-03-24 66 views
0

我想:點擊按鈕=>選擇文件=>點擊「確定」(或雙擊文件)=>上傳自動啓動。用Rails上傳文件?

我怎樣才能實現這一點與鐵軌?

+0

谷歌爲Uploadify,回形針,或Carrierwave;嘗試一下,然後回到實施問題 – 2011-03-24 13:18:10

回答

5

控制器

def file_upload 
    begin 
     ModelName.file_upload(params[:upload]) 
     flash[:notice] = "File has been uploaded successfully" 
     redirect_to :action => "method_name" 
    rescue Exception => e 
     flash[:error] = "Error with upload! Please retry." 
    end 
    end 

型號

def self.file_upload(upload) 
    name = upload.original_filename 
    directory = "#{DIR_PATH}" 
    # create the file path 
    path = File.join(directory, name) 
    # write the file 
    File.open(path, "wb") { |f| f.write(upload.read) } 
    end 

查看

 <% form_tag({:controller => "controller_name", :action => "file_upload"}, {:multipart => true}) do%> 
      <div class="fileinputs"> 
      <input type="file" name="upload" id="upload" class="file" onchange="this.form.submit();" /> 
      <div class="fakefile"> 
       <input class="upload_btn"/> 
      </div> 
      </div> 
     <% end %> 

CSS

div.fileinputs { 
    position: relative; 
} 

div.fakefile { 
    position: absolute; 
    top: 0px; 
    left: 0px; 
    z-index: 1; 
} 

input.file { 
    position: relative; 
    text-align: right; 
    -moz-opacity:0 ; 
    filter:alpha(opacity: 0); 
    opacity: 0; 
    z-index: 2; 
} 

input.upload_btn { 
    background:transparent url(/images/upload_btn.gif) no-repeat scroll 0px 0px ; 
    width:79px; 
    height:26px; 
    cursor:pointer; 
    border:0px; 
} 

input.upload_btn:hover { 
    background:transparent url(/images/upload_btn.gif) no-repeat scroll 0px -40px ; 
} 
1

您可以使用回形針的建議,但我從你的問題了解你想廢除'提交'按鈕?

的JavaScript用於偵聽文件字段onChange事件,並提交形式:

:onchange => "this.form.submit();"