How to show local picture in web page?

前端 未结 6 2056
遇见更好的自我
遇见更好的自我 2020-11-29 05:48

I need to show a picture on web page without uploading it. something like

 
         


        
6条回答
  •  一整个雨季
    2020-11-29 06:38

    You can do that easily using FileReader.readAsDataURL(). The user chooses an image and you can display it without needing to upload it.

    For more info see https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL

    Here is the code:

    function previewFile() {
        // Where you will display your image
        var preview = document.querySelector('img');
        // The button where the user chooses the local image to display
        var file = document.querySelector('input[type=file]').files[0];
        // FileReader instance
        var reader  = new FileReader();
    
        // When the image is loaded we will set it as source of
        // our img tag
        reader.onloadend = function () {
          preview.src = reader.result;
        }
    
        
        if (file) {
          // Load image as a base64 encoded URI
          reader.readAsDataURL(file);
        } else {
          preview.src = "";
        }
      }
      
    Image preview...

提交回复
热议问题