Vaibhav Rajput
Vaibhav Rajput

Reputation: 189

Rails undefined method `name' for nil:NilClass on FileUpload Too much unknown

I am getting undefined method `name' for nil:NilClass on simple file upload form.

View

<%= form_tag({action: :upload}, multipart: true) do %>
  <%= file_field_tag 'picture' %>
  <%= submit_tag "Upload & Produce Result" %>
<% end %>

Controller

def upload
  file_name = params['picture']
  if file_name[-4,4] != ".txt"
    respond_to do |format|
      flash[:notice] = "Please upload only txt file"
      format.html { redirect_to :action => :index }
    end
  end
  File.open(Rails.root.join('public', 'uploads', file_name.original_filename), 'w') do |file|
    file.write(file_name.read)
  end
end

Route

root :to => 'home#index'
post 'upload', to: 'home#upload'

Post Parameters

{"utf8"=>"✓",
 "authenticity_token"=>"HPM76LFj/3Pt7ur1EfMz4SR5T8A9gvoe+JRmneHbu5c=",
 "picture"=>#<ActionDispatch::Http::UploadedFile:0x007f7418370210 @tempfile=#  <Tempfile:/tmp/RackMultipart20130907-9689-viscwz>,
 @original_filename="data.txt",
 @content_type="text/plain",
 @headers="Content-Disposition: form-data; name=\"picture\";   filename=\"data.txt\"\r\nContent-Type: text/plain\r\n">,
 "commit"=>"Upload & Produce Result"}

Even I tried with

raise params.to_yaml

It is giving same error.

Any help would be appreciated.

Thanks.

Upvotes: 2

Views: 2495

Answers (1)

amine
amine

Reputation: 522

You are considering params['picture'] as a string while the Post parameters you gave show that params['picture'] is an 'ActionDispatch::Http::UploadedFile' object

So, you could try to replace params['picture'] with

params[:picture].original_filename

You can also get the rest of the file upload params: params[:picture].tempfile, params[:picture].headers, params[:picture].content_type

You can also refer to this post with a similar issue Reading in file contents rails

Upvotes: 2

Related Questions