html – 如何在网页上显示本地图片?

前端之家收集整理的这篇文章主要介绍了html – 如何在网页上显示本地图片?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要在网页上显示图片而不上传.就像是
<img id="RuPic" src="file://localhost/D:/folder/image.jpg"/>

怎么做?

解决方法

您可以使用FileReader.readAsDataURL()轻松地执行此操作.用户选择图像,您可以显示它,而无需上传它.

欲了解更多信息,请参阅https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL

这是代码

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 = "";
    }
  }
<input type="file" onchange="previewFile()"><br>
  <img src="" height="200" alt="Image preview...">
原文链接:https://www.f2er.com/html/224378.html

猜你在找的HTML相关文章