Search code examples
rubysinatra

Multiple file upload with ruby & sinatra


I'm using the following code to upload a single file through a form:

app.rb

@filename = params[:file][:filename]
file = params[:file][:tempfile]

File.open("./public/#{@filename}", 'wb') do |f|
 f.write(file.read)
end

string_file.erb:

<input type='file' class='form-control' id='<%= array['id'] %>'name='file[]' value='<%= default_value %>' <%= constraints %> style="display: none;" multiple>

How do I loop through to write multiple files to the filesystem?


Solution

  • this is my solution

    puts params['images'].map{ |f| f[:filename] }.join(";")
    k = params['images'].map{ |f| f[:filename] }.join(";")
    $param = k.chomp.split(";")
    array_length = $param.length       # or $param.size
    array_lengthx = array_length - 1
    puts "length of $param is : #{array_length}"
    
    i = 0
    i = i - 1
    puts array_lengthx
    puts i
    while i.to_i < array_lengthx do
      i =i+1
      puts i
      @filename = params[:images][i][:filename]
      file = params[:images][i][:tempfile]
      path = "/home/user/Descargas/sinatra_ajax-master/#{@filename}"
      File.open("/home/user/Descargas/sinatra_ajax-master/#{@filename}", 'wb') do |f|
        f.write file.read
      end
    end
    

    this is html code:

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