Ruby on rails 如何使用Net::FTP将文件复制到单独的服务器上?

Ruby on rails 如何使用Net::FTP将文件复制到单独的服务器上?,ruby-on-rails,ruby,ftp,net-ftp,Ruby On Rails,Ruby,Ftp,Net Ftp,我正在构建一个Rails应用程序,在注册时为每个用户创建一个bookmarklet文件。我想将该文件保存到远程服务器上,所以我正在尝试Ruby的Net::FTP,基于 我尝试了以下代码: require 'net/ftp' FileUtils.cp('public/ext/files/script.js', 'public/ext/bookmarklets/'+resource.authentication_token ) file = File.open('public/ext/

我正在构建一个Rails应用程序,在注册时为每个用户创建一个bookmarklet文件。我想将该文件保存到远程服务器上,所以我正在尝试Ruby的Net::FTP,基于

我尝试了以下代码:

  require 'net/ftp'

  FileUtils.cp('public/ext/files/script.js', 'public/ext/bookmarklets/'+resource.authentication_token )
  file = File.open('public/ext/bookmarklets/'+resource.authentication_token, 'a') {|f| f.puts("cb_bookmarklet.init('"+resource.username+"', '"+resource.authentication_token+"', '"+resource.id.to_s+"');$('<link>', {href: '//***.com/bookmarklet/cb.css',rel: 'stylesheet',type: 'text/css'}).appendTo('head');});"); return f }
  ftp = Net::FTP.new('www.***.com')
  ftp.passive = true
  ftp.login(user = '***', psswd = '***')
  ftp.storbinary("STOR " + file.original_filename, StringIO.new(file.read), Net::FTP::DEFAULT_BLOCKSIZE)
  ftp.quit()
需要“net/ftp”
cp('public/ext/files/script.js','public/ext/bookmarklets/'+resource.authentication_标记)
file=file.open('public/ext/bookmarklets/'+resource.authentication_-token,'a'){f|f.puts(“cb|bookmarklet.init(''+resource.username+“,'+resource.authentication_-token+”,“+resource.id.to_-s+”);$('',{href:'/***.com/bookmarklet/cb.css',rel:'stylesheet',type:'text/css'>)。追加到('head');););返回f}
ftp=Net::ftp.new('www.**.com')
ftp.passive=true
ftp.login(用户='***',psswd='***')
storbinary(“STOR”+file.original\u文件名,StringIO.new(file.read),Net::ftp::DEFAULT\u BLOCKSIZE)
ftp.quit()

但是我得到一个错误,文件变量为零。我可能在这里做错了几件事。我是Ruby和Rails的新手,欢迎您的帮助

File.open的块形式不会返回文件句柄(即使返回,也会在该点关闭)。也许可以将代码大致更改为:

require '…'
FileUtils.cp …
File.open('…','a') do |file|
  ftp = …
  ftp.storbinary("STOR #{file.original_filename}", StringIO.new(file.read))
  ftp.quit
end
或者:

require '…'
FileUtils.cp …
filename = '…'
contents = IO.read(filename)
ftp = …
ftp.storbinary("STOR #{filename}", StringIO.new(contents))
ftp.quit

File.open
的块形式不会返回文件句柄(即使返回,也会在该点关闭)。也许可以将代码大致更改为:

require '…'
FileUtils.cp …
File.open('…','a') do |file|
  ftp = …
  ftp.storbinary("STOR #{file.original_filename}", StringIO.new(file.read))
  ftp.quit
end
或者:

require '…'
FileUtils.cp …
filename = '…'
contents = IO.read(filename)
ftp = …
ftp.storbinary("STOR #{filename}", StringIO.new(contents))
ftp.quit

@请注意,您可能真正想要的是:
File.open(“…”,“a”){| File |…ftp.storbinary(“STOR…”,File)…}
;具体来说,您确定需要一个
StringIO
对象吗?@BonChampion请注意,您可能真正想要的是:
File.open(“…”,“a”){File | ftp.storbinary(“STOR…”,File)}
;具体来说,您确定需要一个
StringIO
对象吗?