Is it possible to replace an image with another one selected by the user on the fly via jQuery alone?

前端 未结 1 1595
有刺的猬
有刺的猬 2020-12-22 09:31

I\'m having the user select an image and I want to change the one shown on the fly without having to rely on server-side scripts like PHP?

Basically, I have an HTML

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-22 10:03

    You can use FileReader API.

    The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer.

    Its method FileReader.readAsDataURL()

    The readAsDataURL method is used to read the contents of the specified Blob or File.

    Note: It works in Modern browsers

    $(document).ready(function() {
    
      $('#file').change(function(e) {
    
        var reader = new FileReader();
        reader.onload = function(e) {
          $('#imagedisplay').attr('src', e.target.result);
        }
        reader.readAsDataURL(this.files[0]);
    
      });
    });
    
    
    

    0 讨论(0)
提交回复
热议问题