Thursday, August 9, 2007

Getting a file to Rails

1.1. Getting a file to Rails

We need a page that allows the user to choose a file to upload to our server.

Create a form that uses POST and set the enctype to ”multipart/form-data”

This can be done using the form_tag helper

<%= form_tag({:action=>'save_picture'}, :multipart => true)%> 

Example

Put the following into the appropriate view file:

<%= form_tag({:action=>'save_picture'}, :multipart => true)%>  <input type="file" name="picture_file" />  <input type="submit" name="Upload" /> </form>

Users require a specifically configured form before they can select and transfer a file to be processed by your application on the server.

While there are a number of ways of producing the desired form, we used the form_tag helper to build the required opening form tag.

Set method=”post”

Because of the mechanics of http, html and how browsers work, file uploads will not work with method="get". You can read more about the difference between GET and POST.

Set the encoding

Make sure that you set the encoding attribute to multipart/form-data. You want the final product to look something like:

<form action="/book/upload_attachment" method="POST" enctype="multipart/form-data" />

No comments:

analytics