Hi again fellows. Well this time bringing to you the marvelous method to upload a file through Ruby CGI, yep, as you seen on… well I don’t know where.

If you dont know how to make a basic CGI app in Ruby, please read this.

Now, if we have the next HTML form to upload files:

<form method="POST" enctype="multipart/form-data" action="uploader.rb">
<label>File:<input type="file" name="file" size="100"/></label> <br />
<input type="submit" value="Go!" />
</form>

It’s easy to know which that form sends the data to uploader.rb. So let’s take a look into that Ruby script.

#!/usr/bin/env ruby

cgi = CGI.new
puts cgi.header
params = cgi.params

So far nothing new. But now lets check if someone send us a file:

if params.has_key?"file"
 #do something with that
end

Again, nothing new. Now comes funny part.

file = params["file"].first
server_file = 'files/' + file.original_filename

First line takes a Ruby object of a class StringIO(not String!) that’s something like a mutant, a mix between an IO object and a String, but none of them… weird class, here is the file that user uploads.

Second line it’s the name(path included) which we are to save the file into the server, yes, this is just a String.

Now we want to save the file in the server, to do that we just take the original file and write it’s content to the server file:

File.open(server_file.untaint, "w") do |f|
    f << file.read
end

Now the job it’s done, your code now looks like:

#!/usr/bin/env ruby

cgi = CGI.new
puts cgi.header
params = cgi.params

if params.has_key?"file"
    file = params["file"].first
    server_file = 'files/' + file.original_filename
    File.open(server_file.untaint, "w") do |f|
        f << file.read
    end
end

Now you can do something with that file.

Happy hacking!.

One response »

  1. don says:

    thanks. everyone is past cgi, but im just learning. started with rails but then had to start over because i wanted to know what it was doing. so first i figure out the basics of form=>cgi=>ruby. then i move on to rack, then get back into rails

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s