Skip to content

Instantly share code, notes, and snippets.

@lchanmann
Created January 28, 2011 02:13
Show Gist options
  • Select an option

  • Save lchanmann/799695 to your computer and use it in GitHub Desktop.

Select an option

Save lchanmann/799695 to your computer and use it in GitHub Desktop.
sinatra application with file_uploader
require 'rubygems'
require 'haml'
require 'sinatra'
require 'sinatra/flash'
require 'file_uploader'
enable :sessions
get '/' do
haml :index
end
post '/upload' do
FileUploader.create.save(params[:file]) do |path|
flash[:upload] = "#{path} is saved."
end
redirect '/'
end
__END__
@@ layout
%html
%head
%title File Uploader
%body
= yield
@@ index
%h1 File Uploader
- if flash[:upload]
%div{:style => 'color:green'}= flash[:upload]
%form{:action => '/upload', :method => 'post', :enctype => 'multipart/form-data'}
%label{:for => 'file'} Select file:
%input{:type => 'file', :id => 'file', :name => 'file'}
%input{:type => 'submit', :value => 'Upload'}
@burningTyger
Copy link
Copy Markdown

You should mention that path is actually a File object and not just a String with a path in it. In Sinatra you might want to just have the filename as you don't access /public/upload/filenmae. You want to use /upload/filename So if you want to access a newly created file you want ot use "/upload/#{path.basename}". Took me a while to look through all the classes to make sure this works.

@lchanmann
Copy link
Copy Markdown
Author

I actually return path of the uploaded file as String not a File object

@burningTyger
Copy link
Copy Markdown

This is strange. Uploads are not complete. I tried with several images and always the last couple of bytes are missing. i.e. in a picture the lower right corner is missing. Is this a problem with the buffered stream? I use sinatra 1.2.1 and thin 1.2.10

@lchanmann
Copy link
Copy Markdown
Author

Last broken bytes problem is fixed on v0.2.1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment