Sylar Sylar - 1 month ago 18
Javascript Question

Preview last uploaded image

I'm using an old project where I could upload many images but for this one, I only need just one. When uploaded, I should see what's uploaded (preview). When first uploaded, I see the image. If uploaded a different image, I still see the first image. I dont want that, I need to preview the last uploaded image.

JavaScript:

$('.receipt.upload').on('change', function(e) {
let id = e.target.id;
let files = e.target.files;
let image = files[0];
let reader = new FileReader();
reader.onload = function(file) {
let img = new Image();
console.log(file);
img.src = file.target.result;
$('.'+id).replaceWith(img);
}
reader.readAsDataURL(image);
//console.log(files);
});


Rails html.erb:

<div>
<%= image_tag('/assets/receipt/missing-receipt.jpg', class: "receipt#{contract.id}") %>
</div>

// Inside a form
<div>
<%= f.file_field :receipt, id: "receipt#{contract.id}" , class: "receipt upload"%>
</div>


Change these makes no difference:

let files = e.target.files[0];
let image = files;

Answer

Created <img> img does not have .className set to <input type="file"> .id. At second change event no element exists in document with id at jQuery() call $('.'+id).

Set the .className of replacement element img to id.

$('.receipt.upload').on('change', function(e) {
  let id = e.target.id;
  let files = e.target.files;
  let image = files[0];
  let reader = new FileReader();
  reader.onload = function(file) {
    let img = new Image();
    img.className = id; // set `img` `.className` to `id`
    console.log(file);
    img.src = file.target.result;
    $('.'+id).replaceWith(img);
  }
  reader.readAsDataURL(image);
});