2011-03-07 43 views
12

由于Heroku不允许将动态文件保存到磁盘,所以我遇到了一个两难的局面,希望能够帮助我克服困难。我有一个可以在RAM中创建的文本文件。问题是我无法找到一个允许我将文件流式传输到另一个FTP服务器的gem或函数。我使用的Net/FTP gem要求我先将文件保存到磁盘。有什么建议么?如何在没有先保存文本文件的情况下在Ruby中进行FTP

ftp = Net::FTP.new(domain) 
ftp.passive = true 
ftp.login(username, password) 
ftp.chdir(path_on_server) 
ftp.puttextfile(path_to_web_file) 
ftp.close 

ftp.puttextfile函数是需要物理文件存在的东西。

回答

19

StringIO.new规定,就像一个打开的文件的对象。通过使用StringIO对象而不是文件,很容易创建像puttextfile这样的方法。

require 'net/ftp' 
require 'stringio' 

class Net::FTP 
    def puttextcontent(content, remotefile, &block) 
    f = StringIO.new(content) 
    begin 
     storlines("STOR " + remotefile, f, &block) 
    ensure 
     f.close 
    end 
    end 
end 

file_content = <<filecontent 
<html> 
    <head><title>Hello!</title></head> 
    <body>Hello.</body> 
</html> 
filecontent 

ftp = Net::FTP.new(domain) 
ftp.passive = true 
ftp.login(username, password) 
ftp.chdir(path_on_server) 
ftp.puttextcontent(file_content, path_to_web_file) 
ftp.close 
+0

非常感谢您的支持!帮助我从Rails应用上传文件。任何想法在哪里预期错误? – aaandre 2012-10-04 00:13:16

5

Heroku的David对我进入那里的支持票给予了迅速的回应。

您可以使用APP_ROOT/tmp进行临时文件输出。在此目录中创建的文件的存在并不保证在单个请求的生命周期之外,但它应该适用于您的目的。

希望这有助于 大卫

+0

谢谢大家的回应。继续Heroku的伟大工作! – scarver2 2011-11-09 13:09:58

+0

Ruby提供'Tempfile':https://ruby-doc.org/stdlib-1.9.3/libdoc/tempfile/rdoc/Tempfile.html – plombix 2017-06-01 13:46:05

相关问题