Jquery: How to dynamically SHOW image using the “value” of <input type=“file”> Field

后端 未结 2 1984
天命终不由人
天命终不由人 2021-01-04 10:58

I was wondering whether there is a way to dynamically display an image that a user just uploaded to the input type=\"file\" field.

For example, so far I have the fol

相关标签:
2条回答
  • 2021-01-04 11:21

    Use this code. It will work:

    <!-- Java script code, use jquery library. -->
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
    
    <script type="text/javascript">
        function showimagepreview(input) 
        {
          if (input.files && input.files[0]) 
          {
            var filerdr = new FileReader();
            filerdr.onload = function(e) {
                $('#imgDisplayarea').attr('src', e.target.result);
            };
            filerdr.readAsDataURL(input.files[0]);
          }
        }
    </script>
    
    <!-- HTML -->
    <form>
        <div>
            <input type="file" name="imgShow" id="imgShow" onchange="imagePreview(this)" />
        </div>
        <img id="imgDisplayarea"/>
    </form>
    
    0 讨论(0)
  • 2021-01-04 11:32

    Take a look at this sample, this should work: http://jsfiddle.net/LvsYc/

    HTML:

    <form id="form1" runat="server">
        <input type='file' id="imgInp" />
        <img id="blah" src="#" alt="your image" />
    </form>
    

    JS:

    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);
    });
    
    0 讨论(0)
提交回复
热议问题