2012-07-16 3 views
0

file_field를 통해 파일을 선택하고 싶을 때 파일에 'nil'오류가 발생합니다. 여기에 오류가 있습니다 : "No such file or directory - Book1.csv"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 
    @[email protected]+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 %> 

답변

1

당신이 경로 대신 실제 경로로 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 및 파일 업로드는 그다지 좋은 조합이 아닙니다. ^^

+0

흠 ... 그 말이하지만 지금은 오류가있어 : Book1.csv "에 대한 정의되지 않은 메서드'임시 파일 '을'에 PARAMS을 변경"문자열 "나는 할 수 있도록 할 필요가 있나요 이 메서드의 호출? – user1480797

+1

포스트 대신 – davidb

+0

mg을 사용 해보십시오. 생명의 은인입니다! 하하하 지금 작동합니다! 고마워요! :디 – user1480797

0

6/27/2017 - 내가 같은 상황에 있다면 누군가에게 도움이되기를 바랍니다.

= 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>> 
관련 문제