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.