2

我的视图包含各种员工的详细信息,我必须为每个员工上传图像并最后保存。我想在保存之前查看每个图像的图像预览,但它需要 localhost 路径并且不显示图像预览。它显示错误:“NetworkError:404 Not Found -localhost:3000/rails.png”

在视图中

<% @person.each do |person| %>

<td><%= person.name %></td>
<td><%= person.date %></td>
<td><input id="<%= person.id %>"  type='file' class="imageUploader" multiple="true" ></td>

 <td class="image_container"> <img id="image_<%= person.id %>" src="#" alt="Image" width="100" height="100"></td>` here
</tr>
  <% end %>

在 application.js::

    $('.imageUploader').change(function() {
 var target_image = $(this).val();
 $(this).parent('td').parent("tr").children('td.image_container').html("<img src="+target_image+">");
 console.log(target_image);
});
4

2 回答 2

1

Guyz,还有一个......`

    FILEFIELD = {}
     $(document).ready(function() {    

     $('.files').change(function() {

        FILEFIELD = $(this)
        var fr = new FileReader;


        fr.onload = function() {
            var img = new Image;
            img.onload = function() {
           var c=$(FILEFIELD).parent("td").parent("tr").children("td").children(".images")[0];
                var ctx=c.getContext("2d");
                ctx.drawImage(img,0,0,50,50);      

         }
            img.src = fr.result;

        };

        fr.readAsDataURL(this.files[0]);

    });
});

最后工作

于 2013-01-11T11:14:04.850 回答
0

好吧,我按照您所说的进行了尝试,并在我的应用程序中获得了图像预览:

我的看法

<% if current_user %>
   <p>Welcome <%= current_user.email %></p>
   <tr><input type="file" id="files" name="files[]" multiple />
   <img id="list" src="#" alt="Image" width="100" height="100"></img></tr>
<% end %>


<style>
  .thumb {
    height: 75px;
    border: 1px solid #000;
    margin: 10px 5px 0 0;
  }
</style>


<script type="text/javascript">
  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = ['<img class="thumb" src="', e.target.result,
                            '" title="', escape(theFile.name), '"/>'].join('');
          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>

如您所见,上面的代码是由我在上传前考虑单个用户图像预览完成的。但是你可以通过为多个用户更改查询和一些代码来为多个用户做同样的事情。

干杯!

于 2013-01-10T10:57:00.077 回答