Ruby Net::FTP Tutorial
Mar 29, 2009
Recently, at Plexus, a client needed the ability to import photos to their site from a remote FTP server. Perfect opportunity for me to learn about Net::FTP. Turns out it was surprisingly simple.
Let's say we want to login to the server 'ftp.sample.com' with the username 'test' and the password 'pass', then switch to the directory 'source/files' and get the file 'photos.zip'. There are a couple ways to do this. First, we have to create and FTP connection with:
require 'net/ftp' # Login to the FTP server ftp = Net::FTP.new('ftp.sample.com', 'test', 'pass') # OR ftp = Net::FTP.new('ftp.sample.com') ftp.login('test', 'pass') # Switch to the desired directory ftp.chdir('source/files') # Get the file we need and save it to our 'ftp_photos' directory ftp.getbinaryfile('photos_2009-03-29.zip', 'ftp_photos/photos.zip') # We're done, so we need to close the connection ftp.close
You can also accomplish the same thing by passing a block to the open method, like so:
require 'net/ftp' Net::FTP.open('ftp.sample.com') do |ftp| ftp.login('test', 'pass') ftp.chdir('source/files') ftp.getbinaryfile('photos_2009-03-29.zip', 'ftp_photos/photos.zip') end
Pretty straightforward and simple.