Spencer Hire
Spencer Hire

Reputation: 763

Rails form tags

I have a form to allow the user to upload an image file, but i currently have it in text format, so they enter the file name of the image, but i would like to have it so they click a select button to upload the file rather than typing it in, and then when the file is selected from their hard drive, it will show in the textbox next to the button, thanks.

<%= form_for(@question) do |f| %>
  <p>
    <%= f.label :question %><br/>
    <%= f.text_field :question, autofocus: true %>
  </p>
  <p>
    <%= f.label :description %><br/>
    <%= f.text_area :description, cols: 40, rows: 7 %>
  </p>
  <p>
    <%= f.label :posted_by %><br/>
    <%= f.text_field :posted_by, size: 5 %>
  </p>
  <p>
    <%= f.label :image_file_name %><br/>
    <%= f.text_field :image_file_name, size: 30, placeholder: 'GIF, JPG, or PNG file' %>
  </p>
  <p>
    <%= f.label :posted_at %><br/>
    <%= f.date_select :posted_at %>
  </p>
  <p>
    <%= f.submit %>
    <%= link_to('Cancel', questions_path) %>
  </p>
<% end %>

Upvotes: 1

Views: 85

Answers (3)

Pavan
Pavan

Reputation: 33542

You can use file_field instead of text_field which allows to upload a file.

<%= f.file_field :image_file_name,accept: 'image/png,image/gif,image/jpeg',:multiple => true %>

:multiple - If set to true, in most updated browsers the user will be allowed to select multiple files.

:accept - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.

For more details, see this API

Upvotes: 2

D.Fux
D.Fux

Reputation: 376

Try to use the file_field instead of text_field.

<%= f.text_field :image_file_name, accept: 'image/png,image/gif,image/jpeg' %>

See more: FormHelper.html#method-i-file_field

Upvotes: 0

Related Questions