Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 951
Bob Avatar asked Apr 25 '10 21:04

Bob


2 Answers

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.

like image 110
Bob Avatar answered Oct 30 '22 22:10

Bob


Seems to me that ftp.putbinaryfile just wants the path and name of the file as the first parameter.

like image 24
Josh Avatar answered Oct 30 '22 22:10

Josh