Firefox, since version 3, has supported 'sendAsBinary()', a 'new file
transfer' method on the XMLHttpRequest object. And in the latest
Firefox beta also supports drag-and-drop.
There is some lovely sample code that combines these two features
posted on the CSS.Ninja blog at:
http://www.thecssninja.com/javascript/drag-and-drop-upload
But the author's code is designed to work with a minimal PHP demo app.
I thought that I would try to get a RoR version working.
The crux of the JavaScript code are these 5 lines
var upload_file_url = // restful route to RoR application
var file = // some code to acquire the file
var xhr = new XMLHttpRequest()
xhr.open("POST", upload_file_url);
xhr.overrideMimeType('text/plain; charset=x-user-defined-
binary');
xhr.sendAsBinary(file.getAsBinary());
Well this is all very fine, except that we normally have a line in
application_controller.rb
protect_from_forgery
Which means the server is now expecting an authenticity_token in all
of the requests that it handles (unless specified otherwise)
So, when you execute ' xhr.sendAsBinary(file.getAsBinary())' the
server rejects the request because there is no 'authenticity_token'.
Well, would it work to incorporate the authenticity_token, and any
other useful file characteristics in the url? I defined a route in
routes.rb like so:
map.file_upload '/
file_upload/:authenticity_token/:user_id/:md5/:name/:suffix/
create', :controller=>'uploaded_files', :action=>'create', :method=>'post'
And in the JavaScript I extract the authenticity_token from the page
and incorporated it into the 'upload_file_url' along with the other
interesting parameters.
And it works... sort of.
If I pretty-print out the params variable this I can see all of the
attributes I incorporated into the URL
{"name"=>"les-amis2",
"method"=>"post",
"authenticity_token"=>
"8a576fa97709c92e102eb5da515481009e2bf5044caa2e014ef6004dde58f5c4",
"action"=>"create",
"user_id"=>"2",
"suffix"=>"jpg",
"md5"=>"1a8591455122cdb9ff1015d694c9c067",
"controller"=>"uploaded_files"}
What is missing however is any reference to the file contents!!!!!!
Does anyone know where it is? I am using 'mongrel' on the server
side, by the way.
Fred Obermann