File Uploads
Handling file uploads is something that doesn't come up too often when writing web applications, but when it does come up, it is nice if one has a way to deal with it easily. This is something that any good framework should be able to deliver.
Under Iowa, file uploads are handled almost like any other form input field. The only difference, in fact, is that rather than receiving into the application the raw data from the input field, one will receive an instance of Iowa::FileData. This object will let one access the name of the transfered file, it's content type, and the file's data. The object also provides a convenience method for writing the file to the filesystem. This particular interface is new, and there are a couple of additions that are planned prior to versions 1.0 of Iowa, but the API as presented here should not change.
Ok. Enough preamble. Let's see how to upload a file!
<form oid="uploadFile" enctype="multipart/form-data">Upload a file: <input type="file" oid="uploaded_file" size="30"><input type="submit" value="Upload" oid="uploadFile"></form>
That's it. Iowa will take care of making sure the file gets delivered to the application properly. The @uploaded_file variable mentioned in the example above will contain nil if the form was submitted without a valid file to upload, or an instance of Iowa::FileData if a file was uploaded.
The Iowa::FileData is actually an Array subclass. The elements of the array hold the file's contents. Thus, one can append additional data to a file by pushing it onto the array. Calling to_s() on the object will return the file content. The content_type() method returns the content type of the file while the name() method returns the path/name of the file as provided by the browser.
Additionally, there is a store() method available. This method will attempt to write the file out to the filesystem at the path/name returned by name(). Because of this, one will probably want to reassign a new name to the file before calling the store() method. To do otherwise would be a serious security problem.
@uploaded_file.name = "/tmp/uploaded_file" @uploaded_file.store


