Normally, to upload file,we will write some codes in the view page
like:
<% form_for(:photo, :url => {:action => :create}, :html =>
{ :multipart => true}) do |form| -%>
Upload A Image:
<%= form.file_field :uploaded_data %>
<%= submit_tag ‘Upload’ %>
<% end -%>
Now,I coded some line of js, append to public/javascript/
application.js
now we just need to change little things as:
change: form_for => remote_form_for
add: :ajaxupload => true
Then we got:
<% remote_form_for(:photo, :url => {:action => :create}, :html =>
{ :multipart => true, :ajaxupload => true}) do |form| -%>
Upload A Image:
<%= form.file_field :uploaded_data %>
<%= submit_tag ‘Upload’ %>
<% end -%>
Now, file upload will post via a iframe without refresh the page.
But how about the rjs?
We won’t forget it.
Add some codes in the controller as bellow:
# iframe request
if params[:HTTP_X_REQUESTED_WITH] && request.post?
render :template => 'photos/create.rjs', :layout =>
false, :content_type => ‘text/html’
else
# normal request
respond_to do |format|
format.html {redirect_to :action => ‘new’, :id => @photo if
request.post?}
format.js
end
end
Now we can render different views by the request type automatically.
The js code could down from:
http://www.rainchen.com/rails/photo_upload/application.js
and a complete photo upload rails demo project:
http://www.rainchen.com/rails/photo_upload/photo_upload.rar
use attachment_fu plugin (require RMagick) and sqlite3 db engline
Tested with IE6,FireFox2.0 on windows XPsp2.
With Safari, upload OK,but evalScripts false.
some helpful links:
attachment_fu tutorial:
http://clarkware.com/cgi/blosxom/2007/02/24#FileUploadFu
RMagick for windows:
http://rubyforge.org/frs/download.php/15132/RMagick-1.14.1_IM-6.3.0-7-Q8.zip
sqlite3 lib for windows:
http://www.sqlite.org/sqlite-3_4_0.zip
http://www.sqlite.org/sqlitedll-3_4_0.zip
last line:
I’m new to Rails, sorry for the rough codes. Any improvement is
wellcome.