如何使用file_file_tag上传文件?

时间:2018-10-30 05:27:50

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2 ruby-on-rails-5

我想以表格形式上传文件,但不希望其字段位于模型中。 所以使用file_filed_tag

at view:
 <%= form_tag services_datainterchange_path, method: :post, remote: true do %>
    <div class="row">
      <div class="col-sm-3 col-md-3">
        <div class="form-group">
          <%= label_tag :file %>
          <%= file_field_tag :file, required: true, class: "form-control", id: "upload_file" %>
        </div>
      </div>
      <div class="col-sm-2 col-md-2">
        <div class="form-group">
          <%= label_tag :name %>
          <%= text_field_tag :name, nil, required: true, class: "form-control", id: "upload_file_name" %>
        </div>
      </div>
      <div class="col-sm-2 col-md-2">
        <div class="form-group">
          <%= label_tag :source_type %>
          <%= select_tag :source_type, options_for_select(ApplicationRecord::SOURCE_TYPE), class: "form-control" %>
        </div>
      </div>
      <div class="col-sm-2 col-md-2">
        <div class="form-group">
          <%= label_tag :final_type %>
          <%= select_tag :final_type, options_for_select(ApplicationRecord::FINAL_TYPE), class: "form-control" %>
        </div>
      </div>
      <div class="col-sm-2 col-md-2">
        <div class="form-group">
          <%= submit_tag "Submit", class: "btn btn-primary" %>
        </div>
      </div>
    </div>
  <% end %>

在控制器上:

  directory = "public/job_files"
  Find.find( directory ) do |fpath|
    if FileTest.file?( fpath )
      fpath.clone(params[:file])
    end
  end

但是文件未上传参数会得到表单提交。 谢谢

1 个答案:

答案 0 :(得分:0)

在控制器中:

  name = params['file'].original_filename

  uploaded_io = params['file']
  File.open(Rails.root.join('public', 'job_files', uploaded_io.original_filename), 'wb') do |file|
    file.write(uploaded_io.read)
  end