Home > Software design >  getting an image from input
getting an image from input

Time:05-01

I'm trying to get a file to change the shape and change the image to what the person inserted.

 <label for="avatarinput">
 <img id="avatar"  style="border-radius: 50%;" height="150" width="150" id="createForm" src= <%= image_url %> >
 </label>
  <input type="file" id="avatarinput"  multiple accept=".jpg,.jfif,.jpeg,.png,.gif" name="filedata" /><br><br>
<script>
$("input[type=file]").on('change',function(){
    let file = $(this).val();
    $('#avatar').attr('src', file);
});
</script>

Not allowed to load local resource: file:///C:/fakepath/scale_1200.jfif

CodePudding user response:

You should use FileReader for read file from the client and set it on img.src Attr.

     $("input[type=file]").on('change',function(element){
            let file = element.target.files[0];
  
             // FileReader support
             if (FileReader && file) {
                var fr = new FileReader();
                 fr.onload = function () {
                     $('#avatar').attr('src', fr.result);
                 }
                 fr.readAsDataURL(file);
             }}
        );
  • Related