Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show local picture in web page?

Tags:

html

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?

like image 843
Artem Avatar asked Feb 05 '11 16:02

Artem


People also ask

How can I display an image from the local machine on a webpage?

To use an image on a webpage, use the <img> tag. The tag allows you to add image source, alt, width, height, etc. The src is to add the image URL. The alt is the alternate text attribute, which is text that is visible when the image fails to load.

How do you display an image on a webpage?

In order to put a simple image on a webpage, we use the <img> element. This is an empty element (meaning that it has no text content or closing tag) that requires a minimum of one attribute to be useful — src (sometimes spoken as its full title, source).


2 Answers

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...">
like image 124
Marcelo Lazaroni Avatar answered Nov 04 '22 02:11

Marcelo Lazaroni


Linking to local image files from remote HTML files used to be possible, but no longer is.

  • In Firefox since version 1.5 (background and config options here)

  • In Internet Explorer I think since Version 8 (I believe I have successfully done this in IE 7, but I can't find hard data)

  • In Chrome probably since forever

See for example this vulnerability report for why this is a good thing.

I don't think there is a workaround. You will just have to upload the image first.

like image 20
Pekka Avatar answered Nov 04 '22 02:11

Pekka