uploadviahttpusingrubycgi-script

Uploading file via HTTP using Ruby cgi-script

Obviously there is form (in upLoad.html) as shown below which resides at the client side, the browser, and transmits a file chosen by browse using POST/GET and invokes the script defined by action.

<form name="requestForm" enctype="multipart/form-data" action="cgi-bin/upLoadFile.rb"

method="POST">

<input type="FILE" name="upfile" value="browse">

<input type="SUBMIT" name="submit" value="submit">

</form>

The contents of the file upLoadFile.rb are as shown below, comments try to explain in more details. I am assuming you have a server like apache or sth installed and configured to run scripts.

#!D:\InstantRails\Ruby\bin\ruby.exe # line 1

# The above line mentions the path of the application to apache which can execute the script currently to be # spawned. It has to be mentioned in line 1 and unindented with #! directive at the beginning.

require "delegate" # some of the files to be included ....

require "tmpdir"

require "cgi"

BASE_DIR = "d:/InstantRails/www/uploads/" # directory where the uploaded files are saved.

cgi = CGI.new("html3") # creates a new session with the params or ENV already set

fObj = cgi.params["upfile"][0] # For the form specified above this is the specific variable that hold # the IO object from which we can simply read the contents of the file # uploaded.

fileName = BASE_DIR + fObj.original_filename # fObj is corresponds to multipart form specified above and # provides a few methods of which original_filename gives # the filename at the client side

File.open( fileName,"w"){|sf|

sf.puts fObj.read # fObj also has a read method which fetches the content of

} # uploaded file

# End of the JOB

# But give some response to the client that his file got uploaded in the server.

cgi.out {

CGI.pretty (

cgi.html {

cgi.head { cgi.title{"UPLOAD FILE"} } +

cgi.body {

cgi.h2{"UPLOADED FILE TO upload DIRECTORY" } +

cgi.a("/uploads"){"list contents of upload"} + cgi.br +

cgi.a("/upLoad.html"){"upload another file"} + cgi.br

}

}

) # CGI.pretty is a method call, not a block

}

Is not it simple?

HOME | ARTICLES | FREINDS | INTERESTS | LINKS | PHOTOGRAPHS | PUBLICATIONS | MISCELLANEOUS