Download video from URL in ruby on rails

2019-08-29 05:53发布

问题:

Currently I am using system command wget to download the video and store in our server:

system("cd #{RAILS_ROOT}/public/users/familyvideos/thumbs && wget -O sxyz1.mp4 #{video.download_url}")

but it's saying:

cd: 1: can't cd to /var/home/web/***.com/public/users/familyvideos/thumbs

Anybody has any idea? Also please provide alternative option to do this.

回答1:

A much better solution would be to use open-uri for this.

http://www.ruby-doc.org/stdlib/libdoc/open-uri/rdoc/

This snippet should do the trick:

url = video.download_url
new_file_path = "#{Rails.root.to_s}/public/users/familyvideos/thumbs/your_video.mp4"
open(new_file_path, "wb") do |file| 
  file.print open(url).read
end


回答2:

It's the cd program complaining, and that's low-level operating system stuff, so the most likely reason is that one or more of the folders after #{RAILS_ROOT}/public doesn't yet exist, or there's a space or some other character in the file path causing problems. Try surrounding the directory name in quotes.

`cd "#{RAILS_ROOT}/public/users/familyvideos/thumbs" && wget -O sxyz1.mp4 #{video.download_url}`

As for better ways, wget is pretty tried and tested so there's nothing wrong with using it, since this is what it was designed for. You could just give it the folder and the filename at the same time instead of cd'ing to it first, however.

`wget -O "#{RAILS_ROOT}/public/users/familyvideos/thumbs/sxyz1.mp4" #{video.download_url}`

Note also I'm using the backtick method of execution instead of system so you're not dealing with escaping double quotes. You could also use %x{wget ...}.