Rails将文件上传到ftp服务器

Bob*_*Bob 13 ftp ruby-on-rails

我正在使用Rails 2.3.5和Ruby 1.8.6并试图弄清楚如何让用户通过我的Rails应用程序将文件上传到另一台机器上的FTP服务器.我的Rails应用程序也将托管在Heroku上,这不便于将文件写入本地文件系统.

index.html.erb

<% form_tag '/ftp/upload', :method => :post, :multipart => true do %>
<label for="file">File to Upload</label> <%= file_field_tag "file" %>
<%= submit_tag 'Upload' %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

ftp_controller.rb

require 'net/ftp'

class FtpController < ApplicationController
  def upload
    file = params[:file]
    ftp = Net::FTP.new('remote-ftp-server')
    ftp.login(user = "***", passwd = "***")
    ftp.putbinaryfile(file.read, File.basename(file.original_filename))
    ftp.quit()
  end

  def index
  end

end
Run Code Online (Sandbox Code Playgroud)

目前我只是想让Rails应用程序在我的Windows笔记本电脑上运行.使用上面的代码,我收到了这个错误

Errno::ENOENT in FtpController#upload
No such file or directory -.... followed by a dump of the file contents
Run Code Online (Sandbox Code Playgroud)

我正在尝试上传CSV文件,如果这有任何区别.谁知道发生了什么?

Bob*_*Bob 21

经过大量研究和敲击后,我最终阅读了putbinaryfile方法的源代码,找出了putbinaryfile限制的解决方法.这是工作代码,替换此行

ftp.putbinaryfile(file.read, File.basename(file.original_filename))
Run Code Online (Sandbox Code Playgroud)

ftp.storbinary("STOR " + file.original_filename, StringIO.new(file.read), Net::FTP::DEFAULT_BLOCKSIZE)
Run Code Online (Sandbox Code Playgroud)

如果你想知道,STOR是一个原始的FTP命令,是的,它来了.我很惊讶这个场景不容易被Ruby标准库处理,当然不是很明显需要做什么.

如果您的应用程序在Heroku上,请添加此行

ftp.passive = true
Run Code Online (Sandbox Code Playgroud)

Heroku的防火墙设置不允许FTP活动模式,也要确保您的FTP服务器支持被动模式.