2012-04-02 38 views
1

我正在构建一个Rails应用程序,它在注册时为每个用户创建一个书签文件。我想将该文件保存到远程服务器上,所以我想根据"Rails upload file to ftp server"尝试Ruby的Net :: FTP。如何使用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() 

但我发现了一个错误,该文件变量是零。我可能在这里做了几件事情。我对Ruby和Rails很新,所以任何帮助都是值得欢迎的。

回答

1

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 
+0

这做到了。非常感谢! – 2012-04-02 22:16:50

+0

@BonChampion请注意,你可能真正想要的是:'File.open('...','a'){| file | ... ftp.storbinary(“STOR ...”,文件)...}';具体而言,你是否确定需要'StringIO'对象? – Phrogz 2012-04-04 03:13:16

相关问题