Rails 上传文件到 ftp 服务器 [英] Rails upload file to ftp server
问题描述
我正在使用 Rails 2.3.5 和 Ruby 1.8.6,并试图弄清楚如何让用户通过我的 Rails 应用程序将文件上传到另一台机器上的 FTP 服务器.此外,我的 Rails 应用程序将托管在 Heroku 上,这不利于将文件写入本地文件系统.
I'm on Rails 2.3.5 and Ruby 1.8.6 and trying to figure out how to let a user upload a file to a FTP server on a different machine via my Rails app. Also my Rails app will be hosted on Heroku which doesn't facilitate the writing of files to the local filesystem.
index.html.erb
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 %>
ftp_controller.rb
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
目前我只是想让 Rails 应用程序在我的 Windows 笔记本电脑上运行.使用上面的代码,我得到了这个错误
Currently I'm just trying to get the Rails app to work on my Windows laptop. With the above code, I'm getting this error
Errno::ENOENT in FtpController#upload
No such file or directory -.... followed by a dump of the file contents
我正在尝试上传一个 CSV 文件,如果这有什么不同的话.有谁知道怎么回事?
I'm trying to upload a CSV file if that makes any difference. Anyone knows what's going on?
推荐答案
经过大量研究和头脑风暴,我最终阅读了 putbinaryfile 方法的源代码,以找出解决 putbinaryfile 限制的解决方法.这是工作代码,替换此行
After much research and head banging, I ended up reading the source code for putbinaryfile method to figure out a workaround for the limitation of putbinaryfile. Here's the working code, replace this line
ftp.putbinaryfile(file.read, File.basename(file.original_filename))
与
ftp.storbinary("STOR " + file.original_filename, StringIO.new(file.read), Net::FTP::DEFAULT_BLOCKSIZE)
如果您想知道,STOR 是一个原始的 FTP 命令,是的.我很惊讶这种情况并不能更容易地由 Ruby 标准库处理,当然需要做什么并不明显.
And in case you are wondering, STOR is a raw FTP command, yeah it came to that. I'm rather surprised this scenario isn't more easily handled by Ruby standard libraries, it certainly wasn't obvious what needed to be done.
如果您的应用在 Heroku 上,请添加此行
And if your app is on Heroku, add this line
ftp.passive = true
Heroku 的防火墙设置不允许 FTP 主动模式,还要确保您的 FTP 服务器支持被动模式.
Heroku's firewall setup does not allow for FTP active mode, also make sure that your FTP server supports passive mode.
这篇关于Rails 上传文件到 ftp 服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!