I have an image element which displays the user’s current profile image. Can I change the src of that image to the image inside the file input?

As you can see in the code below, I have an image element which displays the user’s current profile image. I am wondering would it be possible to change the src='' of the image element to the image which would be stored in the input with type='file'? That is before the file is even uploaded to the file server.

<img class='profile-container-picture' src='{{url("storage/uploads/profile_pictures/edited/".$user->image_file_name)}}'>

<div class="upload-btn-wrapper">
    <button class="btn">Upload a new avatar</button>
    <input type="file" name="file" />
</div>

Answer

This question was asked so many times before. Here, have a look :

function readURL(input) {

  if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      $('#blah').attr('src', e.target.result);
    }

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

$("#imgInp").change(function() {
  readURL(this);
});

Reference: Preview an image before it is uploaded

Leave a Reply

Your email address will not be published. Required fields are marked *