导入CSV - 没有此类文件或目录

时间:2012-07-16 21:32:23

标签: ruby-on-rails csv import filefield

当我想通过file_field选择一个文件时,它会给我一个错误,我的文件是'nil'。这是错误:“没有这样的文件或目录 - Book1.csv”

我可以知道为什么吗?以下是代码:

控制器

def import_csv
@list = List.find(params[:list_id])
@lists = List.all

respond_to do |format|

@csv_text = File.read(params[:list][:file])
@csv = CSV.parse(@csv_text, :headers => true)
@n=0
@csv.each do | row |
  @user_new = User.new
  @user_new.first_name = row[0]
  @user_new.last_name = row[1]
  @user_new.email = row[2]
  @user_new.company = row[3]
  @user_new.address = row[4]
  @user_new.city = row[5]
  @user_new.state = row[6]
  @user_new.zipcode = row[7]
  @user_new.country = row[8]
  @user_new.notes = row[9]
  @user_new.birthday = row[10]
  @user_new.home_number = row[11]
  @user_new.mobile_number = row[12]
  @user_new.list_id = @list.id
  @user_new.save

  @list.subscribers += 1
  @list.save
  @n=@n+1
  GC.start if @n%50==0
  flash[:notice] = "CSV Imported Successfully, with  #{@n} records"                                
end

  format.html { redirect_to lists_url }
  format.json { head :no_content }
end
  end

查看

<%= form_for(:list, :url => list_import_csv_path(@list), :method => :get, :html => {:multipart => true}) do |f| %>
 <table>
    <tr>
        <td><label for="dump_file">Select a CSV File :</label></td>
        <td><%= f.file_field :file %></td>
    </tr>
    <tr>
        <td colspan='2'><%= submit_tag 'Import from CSV file' %></td>
    </tr>
</table>
<% end %>

2 个答案:

答案 0 :(得分:2)

这是因为您尝试将ActionDispatch::Http::UploadedFile对象作为路径而不是真实路径传递。你这样做:

@csv_text = File.read(params[:list][:file])

你应该这样做:

@csv_text = File.read(params[:list][:file].tempfile.to_path.to_s)

当您上传不那么小的文件时,使用:method => :get可能会出现问题。通常GET和文件上传不是这么好的组合。^^

答案 1 :(得分:0)

2017年6月27日 - 如果他们处于和我相同的情况,希望有人能从中受益。

事实证明,我有:

  = form_tag action: :bulk_upload_submit, multipart: true do
    ...
          = file_field_tag :file, accept: 'text/csv'

它将文件params发送为:

"file"=>"subscribers.csv"

我需要更改form_tag以使用路径而不是操作:

= form_tag upload_subscribers_path, multipart: true do

将参数更改为:

"file"=>
  #<ActionDispatch::Http::UploadedFile:0x007ffda857b5e0
   @content_type="text/csv",
   @headers="Content-Disposition: form-data; name=\"file\"; filename=\"subscribers.csv\"\r\nContent-Type: text/csv\r\n",
   @original_filename="subscribers.csv",
   @tempfile=#<File:/var/folders/_4/50fjk9z57x544klj30k0g1780000gn/T/RackMultipart20170627-33947-12xwfow.csv>>