表单: RailsNotes
用户: dreamable
创建日期: 2021-01-18 04:59:06 UTC
更新日期: 2021-01-18 04:59:28 UTC
引用:(Table ID 3, Record ID 15)

标题 :
upload file
笔记 :

guide

  1. form
<%= form_with(url: upload_table_records_path(@table), method: :POST, local: true) do |form| %>
  <div class="form-group row justify-content-center">
    <%= form.file_field :file, class: 'form-control col-6' %>
  </div>

  <div class="actions text-center">
    <%= submit_tag t("upload"), class: "btn btn-primary"%>
  </div>
<% end %>
  1. controller
      f = params[:file]; contents = f.read;
      fpath = f.path;  # same with f.tempfile.path
      File.open(fpath, 'wb') do |file|
        file.write(contents)
        file.close
      end
      Record.from_csv(@table,fpath)
  • Note that params[:file] is ActionDispatch::Http::UploadedFile object
  • It has tempfile stored in tmp files, e.g. /tmp/RackMultipart20210118-18052-19hic1b.csv, which will be deleted when the file is closed.
标签: