既存画像を上書きして、新規画像をプレビューさせたいのですが、下記のコードですと、
既存画像が残ったままになってしまいます。
どなたかわかる方おられたら教えていただけないでしょうか?
よろしくお願いいたします。
rails
1 <%= image_tag @user.picture.url if @user.picture? %> 2 <%= f.label :picture, '画像' %> 3 <%= f.hidden_field :picture_cache %> 4 <img id="img_prev" width=200 height=200 src="#" class="img-thumbnail hidden"/> 5 <%= f.file_field :picture, :id => 'post_post_img' %> 6 <script type="text/javascript"> 7$(function() { 8 function readURL(input) { 9 if (input.files && input.files[0]) { 10 var reader = new FileReader(); 11 12 reader.onload = function (e) { 13 $('#img_prev').attr('src', e.target.result); 14 } 15 reader.readAsDataURL(input.files[0]); 16 } 17 } 18 19 $("#post_post_img").change(function(){ 20 $('#img_prev').removeClass('hidden'); 21 readURL(this); 22 }); 23}); 24</script>
ソースコードです。
<div class="field"> <img alt="95b3b586 9abd 496c 8b50 1aa93fe7bad7" src="/uploads/user/picture/1/95b3b586-9abd-496c-8b50-1aa93fe7bad7.jpg" /> <label for="user_picture">画像</label> <input id="user_picture_cache" name="user[picture_cache]" type="hidden" /> <img id="img_prev" width=200 height=200 src="#" class="img-thumbnail hidden"/> <input id="post_post_img" name="user[picture]" type="file" /> <script type="text/javascript"> $(function() { function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#img_prev').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } $("#post_post_img").change(function(){ $('#img_prev').removeClass('hidden'); readURL(this); }); }); </script> </div>
あなたの回答
tips
プレビュー