How to display local images placed on client machi

2020-03-24 08:36发布

问题:

How to display local images placed on client machine in HTML webpages hosted on a webserver

I'm having few images placed in C:/Images folder so path should be something file:///C:/Images/1.jpg for a image 1.jpg

I'm using the code <img src="file:///C:/Images/1.jpg" /> in sample.html

sample.html when placed on local HDD, shows 1.jpg, but when I put the sample.html file on a web server it doesn't display the image placed on my C: drive.

Is there any way to show images placed on client HDD from a HTML webpage placed on a web server?

I tried even iframe, but no luck.

EDIT: Can I show these images using userscript or firefox addon? I'm actually implementing this thing in my screensaver firefox addon.

回答1:

Web pages aren't allowed to access file:/// URLs for security reasons, there is no way around this. However, if you make the same files accessible via another protocol - this can work. For example, you can put the following line into your add-on's chrome.manifest file:

resource myaddon file:///C:/Images

This will create a resource protocol alias pointing to that directory - and the resource protocol can be used by webpages. Meaning that the pages will be able to use the image C:\Images\1.jpg as resource://myaddon/1.jpg.

You can also add resource protocol aliases dynamically. Just make sure you make only images accessible in this way and not all disk content - you might be opening a security hole otherwise.



回答2:

Use the File API which works on all browsers except IE.

A simple example of this would be:

function ShowImage(filepath){
    var reader=new FileReader(); // File API object
    reader.onload=function(event){
        document.getElementById('myimage').src = event.target.result;
    }
    reader.readAsDataURL(filepath);
}


回答3:

the src attribute is always in the context of the server that is serving the HTML content. I don't think there is a way around that.

So in your example <img src="file:///C:/Images/1.jpg" /> if the host is ip 1.1.1.1 and the client is ip 2.2.2.2

then src would be pointing to 1.1.1.1\file://C:/images/1.jpg <--that's an example not a real protocol.