简体   繁体   中英

Rails upload file to ftp server

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

<% 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

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

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

I'm trying to upload a CSV file if that makes any difference. Anyone knows what's going on?

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))

with

ftp.storbinary("STOR " + file.original_filename, StringIO.new(file.read), Net::FTP::DEFAULT_BLOCKSIZE)

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.

And if your app is on Heroku, add this line

ftp.passive = true

Heroku's firewall setup does not allow for FTP active mode, also make sure that your FTP server supports passive mode.

在我看来,ftp.putbinaryfile只想将文件的路径和名称作为第一个参数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM