2012-07-19 48 views
3

我無法下載從我的導軌服務器上的文件通過Ajax:Ruby on Rails的:由send_file通過jQuery的/ Ajax請求

我在下載控制器表演動作,如果一個參數傳遞給顯示調用send_file行動。

然後我有一個頁面,其中有一個select下拉列表,顯示服務器上的文件列表。當我選擇一個值並點擊下載按鈕時,它會發出一個ajax請求,發送一個GET請求,由我的下載控制器處理。

看着我的服務器日誌,似乎Ajax請求的工作,它說:

Started GET "/download?file=test.txt" for 127.0.0.1 at 2012-07-19 15:13:41 -0700 
Processing by DownloadsController#show as HTML 
    Parameters: {"file"=>"test.txt"} 
Sent file /Users/Admin/Documents/rails_projects/test/public/data/test.txt (0.1ms) 
Completed 200 OK in 0ms (ActiveRecord: 0.0ms) 

但是沒有什麼實際下載。當我實際訪問show頁面時,該文件實際上被下載。我究竟做錯了什麼?

-

的Javascript

<script type="text/javascript"> 
    $(function() { 
     $('#button').click(function() { 
     var s = $("select#dropdown_select").val(); 
       $.ajax({ 
         type: 'GET', 
         url: 'http://localhost:3000/download?file=' + s, 
         dataType: "HTML" 
         }); 
     }) 
    }); 
    </script> 

下載控制器

def show 

    filename = params[:dl] 

    if(filename.nil? == false) 

    path = Rails.root.join('public/data', filename) 
    send_file path, :x_sendfile => true 

    end 
end 
+2

你不能用ajax下載文件,你應該允許用戶提交表單(選擇你提到的)並允許瀏覽器發出請求和響應 – 2012-07-19 22:46:03

回答

7

我有同樣的問題,好樣的,但是,而是採用JS點擊功能,我用鋼軌link標籤。

原來,在我觀點我有一個link_to標籤與remote: true(至極產生Ajax調用)

鏈接目標,產生了PDF的動作。生成PDF(使用蝦和thinreports)併發送,但下載對話框沒有彈出。

所以我刪除remote: true並添加target: '_self',所以它弄成這個樣子(我使用HAML)

!= link_to image_tag('print.png') + (I18n.t :buttons)[:comments][:print], 
    customer_comment_path(@address_book), 
    { target: '_self' } 

和它的工作就好了。

你爲什麼不嘗試用Rail的link標籤重寫代碼?