So i'm building an image previewer during upload in my rails app and I stumbled upon this solution. If I understand it right, there's an onchange listener in the file input and it triggers to change the src of an image tag to the URL of the uploaded file. Here's my version:
function readURL(input) {
console.log(input.files)
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
let imagePreviewContainer = document.getElementById('image-preview-container');
let previewContent = "";
for (let i = 0; i < e.target.result.length; i++) {
previewContent += `<img src="${e.target.result[i]}">`
}
console.log(previewContent);
imagePreviewContainer.innerHTML = previewContent;
}
reader.readAsDataURL(input.files[0]); // convert to base64 string
}
}
let imageFileField = document.getElementById('image-input');
imageFileField.addEventListener('change', () => {
console.log("upload detected");
console.log(this);
readURL(this);
});
here's the .html.erb file:
<div class="modal fade" id="create-item-modal" tabindex="-1" aria-labelledby="create-item-modalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="create-item-modalLabel">New listing</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<%= form_with scope: :item, url: items_path(current_user.id), local: true do |f| %>
<div class="field">
<%= f.label :name, "Item name" %><br />
<%= f.text_field :name, class: "form-control", autofocus: true %>
</div>
<div class="field">
<%= f.label :images %><br />
<%= f.file_field :images, id: "image-input", multiple: true %>
</div>
<div id="image-preview-contaier"></div>
<div class="field">
<%= f.label :description %><br />
<%= f.text_area :description, class: "form-control", size: "30x10", autofocus: true %>
</div>
<%= f.hidden_field :status, value: "open" %>
<%= f.hidden_field :user_id, value: current_user.id %>
<%= hidden_field_tag(:user_id, current_user.id) %>
<div class="modal-footer">
<%= f.submit "Create listing", class: "btn btn-primary" %>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
<% end %>
</div>
</div>
</div>
</div>
With these modifications, I get an empty object in when I console.log(this) so the readURL function doesn't really get the correct argument. What seems to be the problem? Thanks in advance!