Skip to content

Instantly share code, notes, and snippets.

@taf2
Last active November 16, 2016 20:32
Show Gist options
  • Save taf2/9942888 to your computer and use it in GitHub Desktop.
Save taf2/9942888 to your computer and use it in GitHub Desktop.
uploading a file in ruby is hard. ftp is hard.
# fireway configured with: http://major.io/2007/07/01/active-ftp-connections-through-iptables/
require 'net/ftp'
require 'stringio'
# allows us to upload files by content instead of writing to disk first
class Net::FTP
def puttextcontent(content, remotefile, &block)
f = StringIO.new(content)
begin
storlines("STOR " + remotefile, f, &block)
ensure
f.close
end
end
end
def upload_data_buffer(data_buffer)
ftp = Net::FTP.new
remotefile = "data-#{Time.now.strftime("%F")}.txt"
upload_status = false
begin
ftp.debug_mode = true
ftp.passive = true
ftp.connect(ftp_host)
STDERR.puts "FTP connection established"
ftp.login(ftp_user, ftp_pass)
STDERR.puts "FTP login access granted"
ftp.chdir(ftp_dir)
list = ftp.list
STDERR.puts "FTP changed folder to: #{ftp_dir} -> #{list.inspect}\n"
ret = ftp.puttextcontent(data_buffer.read, remotefile)
STDERR.puts "FTP databuffer: #{ret.inspect} -> #{remotefile} -> #{ftp.last_response}"
upload_status = true
rescue => e
STDERR.puts("FTP Error: #{self.id}: #{e.message}\n#{e.backtrace.join("\n")} -> #{e.inspect}")
Rails.logger.error("FTP Error: #{self.id}: #{e.message}\n#{e.backtrace.join("\n")}")
ensure
ftp.close
end
STDERR.puts "FTP upload status: #{upload_status}"
upload_status
end
upload_data_buffer(StringIO.new("this is my fun test file data"))
@taf2
Copy link
Author

taf2 commented Apr 3, 2014

turns out this can be triggered by an FTP server when the folder does not have write permission.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment