如何在没有先保存文本文件的情况下在Ruby中进行FTP [英] How to FTP in Ruby without first saving the text file

查看:98
本文介绍了如何在没有先保存文本文件的情况下在Ruby中进行FTP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于Heroku不允许将动态文件保存到磁盘,所以我遇到了一个困境,我希望你能帮我克服。我有一个可以在RAM中创建的文本文件。问题是我无法找到一个允许我将文件流式传输到另一个FTP服务器的gem或函数。我使用的Net / FTP gem要求我先将文件保存到磁盘。任何建议?

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

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

解决方案

div>

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

  require'net / ftp'​​
require'stringio'

class Net :: FTP
def puttextcontent(content,remotefile,&block)
f = StringIO.new(content)
begin
storlines( STOR+ remotefile,f,&block)
确保
f.close
结束
结束
结束

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

ftp = Net :: FTP.new(域名)
ftp.passive = true
ftp.login(用户名,密码)
ftp .chdir(path_on_server)
ftp.puttextcontent(file_content,path_to_web_file)
ftp.close


Since Heroku does not allow saving dynamic files to disk, I've run into a dilemma that I am hoping you can help me overcome. I have a text file that I can create in RAM. The problem is that I cannot find a gem or function that would allow me to stream the file to another FTP server. The Net/FTP gem I am using requires that I save the file to disk first. Any suggestions?

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

The ftp.puttextfile function is what is requiring a physical file to exist.

StringIO.new provides an object that acts like an opened file. It's easy to create a method like puttextfile, by using StringIO object instead of file.

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

这篇关于如何在没有先保存文本文件的情况下在Ruby中进行FTP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆