rails嵌套表单jquery图像预览

时间:2015-06-25 06:08:34

标签: javascript jquery html ruby-on-rails

我使用带有jquery嵌套形式的rails。如何在自己的图像标记中预览要上传的图像。在上面的图片。每次添加新图片时,都会在第一个图片标记上进行审核。

这是我的HTML代码:

<%= f.fields_for :product_images do |builder| %>

  <div class="row">
    <div class="col-xs-6">

      <div class="form-group">
        <%= f.label 'Upload Image' %>
        <%= builder.file_field :image, class: 'form-control', onchange: 'readURL(this);' %>
        <small class="pull-right">
          <%= builder.link_to_remove "Remove this image" %>
        </small>
      </div>

    </div>

    <div class="col-xs-6">
      <div class="form-group">
        <%= f.label 'Image: ' %> <br>
        <%= image_tag builder.object.image_url(:small), id: 'img_prev' if builder.object.image_url.present? %>
      </div>
    </div>
  </div>

  <% end %>

  <div class="form-group">
    <%= f.link_to_add "Add image", :product_images, class: 'btn btn-success' %>
  </div>

<% end %>

和我的jquery脚本:

// image preview
function readURL(input) {
    if (input.files && input.files[0]) {
      var reader = new FileReader();

      reader.onload = function (e) {
        $('#img_prev')
          .attr('src', e.target.result)
          // .width(150);
          .height(100);
      };

      reader.readAsDataURL(input.files[0]);
    }
}

1 个答案:

答案 0 :(得分:0)

jQuery的:

// Set image preview on selection
function readURL(input, div_id) {
  div_id = "#" + div_id;
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function (e) {
        $(div_id).attr('src', e.target.result);
    }
    reader.readAsDataURL(input.files[0]);
  }
}

滑轨:

<%= f.fields_for :pictures do |pic| %>
    <%= pic.file_field :picture, :onChange => "readURL(this, #{pic.index})" %>
    <img id="<%= pic.index %>" src="<%= image_url 'image-placeholder.png' %>">
<% end %>