本文介绍了如何在网页上显示本地图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在网页上显示图片而无需上传。像

 < img id =RuPicsrc =file:// localhost / D:/ folder / image。 JPG/> 

如何做?

解决方案

您可以使用 FileReader.readAsDataURL()轻松完成此操作。用户选择一个图像,你可以显示它,而不需要上传。



欲了解更多信息,请参阅



以下是代码:

function previewFile(){//显示图片的位置var preview = document .querySelector( 'IMG'); //用户选择本地图像显示的按钮var file = document.querySelector('input [type = file]')。files [0]; // FileReader实例var reader = new FileReader(); //当图片加载时,我们将它设置为//我们的img标签的来源reader.onloadend = function(){preview.src = reader.result; } if(file){//将图像加载为base64编码的URI reader.readAsDataURL(file); } else {preview.src =; }} < input type =fileonchange = previewFile() ><峰; br> < img src =height =200alt =图片预览...>


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

 <img id="RuPic" src="file://localhost/D:/folder/image.jpg"/>

How to do that?

解决方案

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 = "";
    }
  }
  <input type="file" onchange="previewFile()"><br>
  <img src="" height="200" alt="Image preview...">

这篇关于如何在网页上显示本地图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 22:42