Upload image in ruby on rails through AJAX
This is HTML and JavaScript code.
<% remote_form_for(:image_upload_form, :url => "/meeting/save_image/", :html => { :method => :post, :id => 'imgForm', :multipart => true }) do |f| %>
Upload a image: <%= f.file_field :uploaded_image %>
<% end %>
$('#imgForm input').change(function(){
$(this).parent().ajaxSubmit({
beforeSubmit: function(a,f,obj) {
obj.dataType = 'json';
},
complete: function(XMLHttpRequest, textStatus) {
// do what you want after image upload
},
});
});
Controller code.
def save_image
name = params[:image_upload_form][:uploaded_image].original_filename
directory = "public"
# create the file path
path = File.join(directory, name)
# write the file
File.open(path, "wb") { |f| f.write(params[:image_upload_form][:uploaded_image].read) }
render :text => name
end
0 Comment(s)