2017-01-19 27 views
1

我無法在文檔和Google上找到關於Rails上可恢復的下載的任何內容(Ruby)如何在Rails5上下載事件?

我在Linux上使用Ruby 2.4和Rails 5.0.1。我想讓我的用戶通過rails下載文件。 當下載開始我想讓他們暫停恢復它。並且,在每個請求塊我想執行一些功能(事件也許)。

我可以做到PHP/Laravel5。我可以提供可恢復的下載,我可以在的每個請求部分上運行代碼。

我在Rails的網站或Google上找不到任何關於此的東西。這個巨大的框架無法做到嗎?

大注意:

我不是在說直接下載文件。我想控制每個部分。當從x字節到y字節請求時,我想在執行該部分之前執行一些代碼。

任何想法?

+0

[如何從Rails應用程序下載文件]可能重複(http://stackoverflow.com/questions/6392003/how-to-download-a-file-from-rails-application) –

+0

不可以。它只是下載一個文件。我想要控制每個塊/部分並根據請求執行一些代碼。 – Pratha

+2

請參閱第12.3節[Rails指南中的實況串流](http://guides.rubyonrails.org/action_controller_overview.html#streaming-and-file-downloads)。 – 7stud

回答

2

articleofficial documentation的信息。

class DownloadingController < ActionController::Base 
    include ActionController::Live 

    def stream 
    response.headers['Content-Type'] = 'text/event-stream' 
    (params[:from].to_i..params[:to].to_i).each { |i| 
     response.stream.write "hello world #{i}\n" 
     sleep 1 
    } 
    ensure 
    response.stream.close 
    end 
end 

routes.rb

get 'downloading' => 'downloading#stream' 

下水:

curl -i "http://localhost:3000/downloading?from=10&to=20" 

輸出:

HTTP/1.1 200 OK 
X-Frame-Options: SAMEORIGIN 
X-XSS-Protection: 1; mode=block 
X-Content-Type-Options: nosniff 
Content-Type: text/event-stream 
ETag: W/"1f373c782d25c8d804203b14291b315b" 
Cache-Control: max-age=0, private, must-revalidate 
X-Request-Id: 53337282-e382-4807-bdf9-cbf689ac24b2 
X-Runtime: 21.048071 
Transfer-Encoding: chunked 

hello world 10 
hello world 11 
hello world 12 
hello world 13 
hello world 14 
hello world 15 
hello world 16 
hello world 17 
hello world 18 
hello world 19 
hello world 20 

恢復

如果您想恢復以前的下載,您必須檢查request.headers["Range"]並設置:status => "206 Partial Content"以及response.header["Accept-Ranges"] = "bytes"

那些twoanswers可能會幫助你。

+1

下載加速器使用「Content-range」標題字段。因此,我可以使用該頭字段來解析每個請求的塊並將該文件的該部分發送給客戶端,而不是像你的(從/到)GET查詢參數。 – Pratha

+0

在「簡歷」上更新了答案後。謝謝,這就是我想要做的。 – Pratha