Uploading Image in Ajax style with Rails + jQuery.upload
On my way writing Kcanvas, a web app that provides a user a huge canvas to put fragments of information in daily life, I wonder how can I realize Ajax style file upload. Javascript can not deal with local files.
There is a simple jQuery plugin "jQuery.upload" to realize Ajax style file upload. This plugin works quite well.
If you use this plugin with Ruby on Rails, don't forget to send authenticity_token together otherwise the session expires ...
<script> $('#imageUploadButton').click(function() { var csrf_token = $("meta[name=csrf-token]").attr("content"); $('input[type=file]').upload( url, {'authenticity_token' : csrf_token}, function(res) { alert('uploaded.'); }, 'json' ); }); </script> <input type="file" name="upload" /> <input id="imageUploadButton" type="button" value="Upload" />
On the server side, you can receive the data like this:
file = params["upload"] ext = File.extname( params["upload"].original_filename.to_s) filename = File.basename( params["upload"].original_filename.to_s, ext).to_s.gsub(/[\.\s ]+/,"") + ext File.open("#{TEMP_FILE_DIR_IMAGES}/#{filename}", "wb"){ |f| f.write(file.read) }
Happy coding :)