Lokesh
Lokesh

Reputation: 3112

Start a dowload from external link in Rails

I'm trying to write code in my controller download to start a download from some external url say www.abc.com/foo.mp4. So far I have built it this way:

def download
  redirect_to 'www.abc.com/foo.mp4'
end

It works but the problem is that it opens a video in the same tab. What I want is that it should start a download in the browser of this video.

I searched about it in forums but couldn't find any solution. All I found was a way to download the video first using the URL and then provide it as download but that's not what I want. I want the download to start directly from the external URL.

Upvotes: 0

Views: 410

Answers (1)

Marta
Marta

Reputation: 25

I think this might help you: Download from a link with HTML5
In your case it would be:

<a href="www.abc.com/foo.mp4" download="foo4.mp4">download me</a>

That way, from the same webpage you are, when the user clicks on it, it will start the download and you don't go throught the controller, but in case you want to go throught the controller "download" and then just render a page with some kind of information saying that is downloading or something else, then put that link I wrote above somewhere in that page (and if you want, you can give it a class name and with css hide that class so that link is not visible but it is there) and at the end a Javascript function that calls itself when it is loaded and performs the action of clicking to that link:

(function(){
  $('#whateverIdYouGiveToTheHtmlElement').click();
})();

I should clarify that $('#whateverIdYouGiveToTheLink').click(); is jQuery and not pure Javascript, but since you are using Rails I assume the project has jQuery (by default Rails comes with jQuery).

Upvotes: 1

Related Questions