Skip to content

Instantly share code, notes, and snippets.

@kematzy
Created July 10, 2009 09:07
Show Gist options
  • Save kematzy/144365 to your computer and use it in GitHub Desktop.
Save kematzy/144365 to your computer and use it in GitHub Desktop.
class MyApp < Sinatra::Base
# ....
# does nothing other than load the <input type="file"> form...
get '/upload' do
erb(:upload)
end
post '/upload' do
if params[:filedata] # NB!! this depends on the params value you send from the form
# params.inspect
filename = params[:filedata][:filename]
file = params[:filedata][:tempfile]
filepath = File.join(__PATH_TO_YOUR_ROOT, 'public', 'upload_dir', filename)
err = File.open(filepath, 'wb') { |f| f.write(file.read) }
# test if successfully uploaded (uses Kernel#test )
return test(?f,filepath) ? "#{filename} <span>successfully uploaded.</span>" : "Upload Error: #{filename} failed due to = err=[#{err}]"
else
return "Upload Error: Wrong params sent. No file was uploaded. Please check your code."
end
end
## SAFARI 3 UPLOAD BUG FIX
get '/safari-upload-fix' do
headers "Connection" => 'close'
''
end
end
###################################
# Add this to fix a really irritating Safari 3 bug (a few hours wasted on it :( )
### Then add this JS (using JQuery) on your upload page
%Q[/* HACK ALERT: Safari 3.x intermittently hangs when making uploads.
* The following code prevents that by doing a AJAX request to the server
* immediately before the upload is submitted. The server returns an empty
* document with the "Connection: close" header, telling Safari to close the active connection.
*/
$('#{submit_btn}').click(function() { if ($.browser.safari) { $.ajax({ url: "/safari-upload-fix", async: false }); } });]
# That all works just fine
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment