Rails form Images

1.3k views Asked by At

This is my form :

<%= form_for @user, validate: true do |f| %>

<div class="well-lg">
  <h4>Personal Details</h4>
  <div class="form-group">
    <%= f.label :Role %> <br />
    <%= f.select :role, options_for_role, {}, prompt: 'Select One',:class=> 'form-control' %>
  </div>
  <div class="form-group">
    <%= f.label :First_Name %><br />
    <%= f.text_field :fname, :class=> 'form-control' %>
  </div>
  <div class="form-group">
    <%= f.label :Last_Name %><br />
    <%= f.text_field :lname, :class=> 'form-control' %>
  </div>
  <div class="form-group">
    <%= f.label :Email_Address %><br />
    <%= f.email_field :email, :class=> 'form-control' %>
  </div>
  <div class="form-group"> 
    <%= f.label :Upload_Image %><br />
    <%= f.file_field :orgimg, :class => 'fileupload' %>
       <div id = 'dvPreview>
       </div>
  </div>
</div>
<% end %>

Everything works fine but I wanted to preview the image which is uploaded in the form so how can I add image_tag with file field or is there any other solution??

Thanks !!!

1

There are 1 answers

0
Nitin Rajan On BEST ANSWER

By using the following code , I was able to preview the image while uploading

<script language="javascript" type="text/javascript">
  $(function () {
      $(".fileupload").change(function () {
          if (typeof (FileReader) != "undefined") {
              var dvPreview = $("#dvPreview");
              dvPreview.html("");
              var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
              $($(this)[0].files).each(function () {
                  var file = $(this);
                  if (regex.test(file[0].name.toLowerCase())) {
                      var reader = new FileReader();
                      reader.onload = function (e) {
                          var img = $("<img />");
                          img.attr("style", "height:100px;width: 100px");
                          img.attr("src", e.target.result);
                          dvPreview.append(img);
                      }
                      reader.readAsDataURL(file[0]);
                  } else {
                      alert(file[0].name + " is not a valid image file.");
                      dvPreview.html("");
                      return false;
                  }
              });
          } else {
              alert("This browser does not support HTML5 FileReader.");
          }
      });
  });