要求 - 我的服务器上托管了一个视频,用户应该可以通过单击链接下载该文件。
我按照http://code.runnable.com/Upd0g0q7JxN6AAIE/how-to-download-a-file-using-ruby-on-rails-提供的说明下载视频文件。
下载需要花费大量时间,然后在浏览器中打开二进制文件。
控制器 - 已编辑 - 完整控制器
class YoutubeDownloadsController < ApplicationController
def index
end
def download
link = params[:link]
#YoutubeDL.download "https://www.youtube.com/watch?v=gvdf5n-zI14", output: Rails.public_path.join('downloads','some_file.mp4')
respond_to do |format|
format.html
format.json
format.js
end
end
def browser_download
send_file Rails.public_path.join('downloads', 'some_file.mp4'), :type=>"video/mp4", :x_sendfile=>true
end
end
查看 -
index.html.erb
<div class="card">
<header class="card-header bg-inverse text-white">
<h3 class="text-left font-weight-bold">Download Videos <small class="font-italic">...for free</small></h3>
</header>
</div>
<div class="col-lg-8" style="margin-top:15%;margin-left:10em;margin-right:10em;">
<%= form_tag("/download",method:"post", remote: true) do %>
<div class="input-group">
<%= text_field_tag 'link', nil, placeholder: 'Paste your youtube link ...', class: "form-control" %>
<!--input type="text" class="form-control" placeholder="Paste your youtube link ..."-->
<span class="input-group-btn">
<%= button_tag "Download!", class: "btn btn-primary" %>
<!--button class="btn btn-primary" type="button">Go!</button-->
</span>
</div>
<% end %>
<div id='file'></div>
<br>
<small><p class="text-muted" style="margin-left:20em;margin-right:20em;">Please thank good samaritans @ <a href="https://rg3.github.io/youtube-dl/">Youtube-dl</a>. They made it possible.</p></small>
</div>
<div class="card">
<footer class="text-right card-footer text-muted bg-info text-white" >
<small><p>Posted by: Tushar Saurabh | Contact information: <a href="mailto:tusharacc@gmail.com">Email Me</a>.</p></small>
</footer>
</div>
download.js.erb
var html = '<a href="<%= browser_download_path %>">Download</a>';
document.getElementById('file').innerHTML = html
路线 -
get '/browser_download', to: 'download#browser_download'
如何避免在浏览器中打开文件。而且,这个过程很慢,有更好更快的方法。