使用ruby&amp ;;多文件上传西纳特拉

时间:2017-04-11 17:46:58

标签: ruby sinatra

我使用以下代码通过表单上传单个文件:

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>

如何循环将多个文件写入文件系统?

1 个答案:

答案 0 :(得分:2)

这是我的解决方案

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

这是html代码:

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