Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple file uploads in Sinatra

I'm writing a simple Sinatra app but having issues having <input type="file" multiple /> not making Rack throw a NoMethodError: undefined method 'bytesize' for (Hash) while reading the files.

The form is written like so:

<form action="/upload" enctype="multipart/form-data" method="post">
    <input type="file" name="images[]" multiple />
</form>

But the receiving end throws the mentioned error, before any of my code executes, that is, Rack is not parsing correctly the input[name=images]. Am I sending the form incorrectly? If I drop the brackets [], then only the last file (of many) is sent, but I feel like I might be missing something...

Just to clarify: this is Sinatra v1.4.3 and Rack v1.5.2, the latter being the one throwing the exception. Full backtrace here.

like image 286
Roberto Avatar asked Dec 01 '25 14:12

Roberto


1 Answers

The only thing that puts me off here is that you don't use the POST method – maybe your issue has to do with that. Anyway, the following code works perfectly for me. I hope this will give you a hint how to fix your code.

require 'sinatra'

get '/' do
  <<-HTML
  <html>
  <head><title>Multi file upload</title></head>
  <body>
    <form action="/upload" method="post" enctype="multipart/form-data">
      <input type="file" name="images[]" multiple />
      <input type="submit" />
    </form>
  </body>
  </html>
  HTML
end

post '/upload' do
  content_type :text

  res = "I received the following files:\n"
  res << params['images'].map{|f| f[:filename] }.join("\n")
  res
end
like image 179
Patrick Oscity Avatar answered Dec 05 '25 14:12

Patrick Oscity