April 26, 2009

Clearing the file upload field

I recently needed to add file upload functionality to a rails app and discovered that HTML doesn't let you clear the file upload field after you have selected a file (in the case where you suddenly changed your mind and decided not to upload anything).

So after searching for a while I found an answer and it isn't pretty. You have to pretty much replace the file upload field with a new one using javascript.

Here is a basic example using jQuery:

In the view:
<%= f.file_field :attachment %>
<%= link_to_function 'clear', clear_js(id, name) %>
where id and name should be the same as your file field. Right now, I'm trying to figure out a way of pulling this info out cleanly from the form builder but not having much progress.

In a helper:
# creates an equivalent file field and replaces the current one
def clear_js(id, name)
%Q[
var newButton = document.createElement("input");
$(newButton).attr("type","file");
$(newButton).attr("id", "#{id}");
$(newButton).attr("name", "#{name}");
$(newButton).attr("size", "30");
$("##{id}").replaceWith(newButton);
]
end
FYI, I read that you can't just alter the value of the field with something like $('input').value = ' ', and for a good reason - then someone could theoretically write a script to set the value to any file on your computer.

No comments:

Post a Comment