125

It works if the html file is local (on my C drive), but not if the html file is on a server and the image file is local. Why is that?

Any possible workarounds?

ZachB
  • 13,051
  • 4
  • 61
  • 89
PeterV
  • 2,792
  • 3
  • 20
  • 22
  • 3
    May I ask why you would want to do such a thing? – Boris Callens Nov 03 '10 at 19:23
  • 2
    @BorisCallens For example I might want to test the change of an image on my staging website, when I have the new image on my own machine and I don't want to go through the whole process of uploading to staging. Seems that the only way to do it would be to change the image in the development environment instead of staging anyways. – xji Feb 02 '15 at 07:47
  • It's also a great way to play a joke on your less technically competent acquaintances, making them think you've hacked into a website. – kingsfoil Apr 20 '16 at 22:21
  • Another way to do this quickly is to upload the file to say, google drive or whatever then copy the image url and paste it inside `src=""` – kingsfoil Apr 20 '16 at 22:28
  • Just use a development webserver on your machine. It's easy nowadays since even PHP comes with one built in. – MauganRa Apr 07 '17 at 06:06

16 Answers16

78

It would be a security vulnerability if the client could request local file system files and then use JavaScript to figure out what's in them.

The only way around this is to build an extension in a browser. Firefox extensions and IE extensions can access local resources. Chrome is much more restrictive.

Bjorn
  • 69,215
  • 39
  • 136
  • 164
  • 2
    still, flash manages to access anything the user selects, even in Chrome – Javier Nov 03 '10 at 19:51
  • 1
    Upvoted this because it answered the why and gave some ways around it. What I'll likely do (and I know I didn't provide much background) is create a local webserver to serve local images. That way the browser can display them. – PeterV Nov 04 '10 at 01:26
  • 1
    Flash can only access local resources with a policy file in place or otherwise it goes into local mode and its restricted in other ways. – Bjorn Nov 04 '10 at 13:09
  • 2
    This paranoid security is only a disturbance. You CAN upload user files to the server with AJAX from a form with field, but if you want to be nice to the user and show a preview, you HAVE to do the round trip and upload the file to the server first. How is it more secure than generating the preview image locally? – MKaama Sep 15 '16 at 10:10
  • 2
    In order to show the user a nice preview YOU HAVE TO DO A ROUND TRIP TO THE SERVER first. It is possible with AJAX. How is uploading a file to the server first more secure than generating the preview image locally? The paranoid security creates only disturbance, but does not solve any problem. – MKaama Sep 15 '16 at 10:17
  • I don't think you are either confused about the question or the answer, as there is nothing upload related in this question. The user is trying to see both local and server content from the server and that's not possible @MKaama – Bjorn Sep 15 '16 at 23:47
  • @javier that's exactly the point and the reason because flash had been deprecated – netalex Apr 13 '21 at 08:06
39

Shouldn't you use file://C:/localfile.jpg instead of C:/localfile.jpg?

double-beep
  • 5,031
  • 17
  • 33
  • 41
AndreDurao
  • 5,600
  • 7
  • 41
  • 61
  • Yeah but this trick will work in Windows systems only. Under Linux you must create a Symlink to the resource and place the link into the same web page and call it using src="...". In other words as far as I've tried the "file://" prefix will not work under Linux systems while will work perfectly under Windows systems. – Power Engineering Nov 18 '20 at 19:39
  • 2
    `file:///localfile.jpg` is correect one for linux – Blanket Fox Mar 14 '21 at 03:09
36

Browsers aren't allowed to access the local file system unless you're accessing a local html page. You have to upload the image somewhere. If it's in the same directory as the html file, then you can use <img src="localfile.jpg"/>

Newtang
  • 6,414
  • 10
  • 49
  • 70
  • I was trying to achieve the same using absolute path "/localfile.jpg" but seems the browser takes it like a "web image" and it does not find it. Thanks! – julianm Sep 28 '20 at 02:04
20

C: is not a recognized URI scheme. Try file://c|/... instead.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
7

Honestly the easiest way was to add file hosting to the server.

  • Open IIS

  • Add a Virtual Directory under Default Web Site

    • virtual path will be what you want to browse to in the browser. So if you choose "serverName/images you will be able to browse to it by going to http://serverName/images
    • Then add the physical path on the C: drive
  • Add the appropriate permissions to the folder on the C: drive for "NETWORK SERVICE" and "IIS AppPool\DefaultAppPool"

  • Refresh Default Web Site

  • And you're done. You can now browse to any image in that folder by navigating to http://yourServerName/whateverYourFolderNameIs/yourImage.jpg and use that url in your img src

Hope this helps someone

foremaro
  • 168
  • 2
  • 12
5

We can use JavaScript's FileReader() and its `readAsDataURL (fileContent function to show local drive/folder file. Bind change event to image then call JavaScript's showpreview function.

<!doctype html>
<html>

<head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;'>
    <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
    <title></title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <script type="text/javascript">
    function showpreview(e) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $("#previewImage").attr("src", e.target.result);
        }
        //Imagepath.files[0] is blob type
        reader.readAsDataURL(e.files[0]);
    }
    </script>
</head>
<body >
    <div>
    <input type="file" name="fileupload" value="fileupload" id="fileupload" onchange='showpreview(this)'>
    </div>
    <div>
        &nbsp;
    </div>
    <div>
    <img width="50%" id="previewImage">
    </div>
</body>
</html>
double-beep
  • 5,031
  • 17
  • 33
  • 41
Ravindra Vairagi
  • 1,055
  • 15
  • 22
  • Chrome throws an error in console "Not allowed to load local resource". – raosaeedali Jun 04 '18 at 06:00
  • 1
    @raosaeedali Sorry for the late response. If we want to display images from local drive into our img tag of HTML page directly then we need to give relative path. Another solution is we get file path from an input type file and assign the file source to the img tag for this I updated the code. – Ravindra Vairagi Jun 29 '18 at 05:39
  • @RavindraVairagi is there a way to display the image without choosing a file in the explorer? I've tried to use your script and I didn't obtained the error of "Not allowed to load local resource" but I wish to find a way to directly print the image, if it exists... – Bando Aug 09 '19 at 08:53
3

IE 9 : If you want that the user takes a look at image before he posts it to the server : The user should ADD the website to "trusted Website list".

2

if you use Google chrome browser you can use like this

<img src="E://bulbpro/pic_bulboff.gif"   width="150px" height="200px">

But if you use Mozila Firefox the you need to add "file " ex.

<img src="file:E://bulbpro/pic_bulboff.gif"   width="150px" height="200px">
Sachindra N. Pandey
  • 1,177
  • 17
  • 15
2

Newtang's observation about the security rules aside, how are you going to know that anyone who views your page will have the correct images at c:\localfile.jpg? You can't. Even if you think you can, you can't. It presupposes a windows environment, for one thing.

Jack Kelly
  • 18,264
  • 2
  • 56
  • 81
  • Unless you can. I haven't given much context in the question, I know :) But in this case we can actually know. – PeterV Nov 04 '10 at 01:36
  • 5
    What if he only plans on having 10 users in an office that all have windows environments and the correct images at c:\localfile.jpg. To that end... he would be completely able to not only know that the correct images are there but control them as well. – Nazca Jan 28 '14 at 00:37
  • This question is valid because his requirement is for a windows environment, serving a very limited audience. For example, I ran into the same problem when I was designing an Arduino based web server where the only client was a windows PC on the same LAN as the Arduino server. The Arduino was too slow in serving images to the client so I needed to store the images on the client machine itself. – PrashanD May 18 '17 at 05:30
2

I see two possibilities for what you are trying to do:

  1. You want your webpage, running on a server, to find the file on the computer that you originally designed it?

  2. You want it to fetch it from the pc that is viewing at the page?

Option 1 just doesn't make sense :)

Option 2 would be a security hole, the browser prohibits a web page (served from the web) from loading content on the viewer's machine.

Kyle Hudson told you what you need to do, but that is so basic that I find it hard to believe this is all you want to do.

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
2

starts with file:/// and ends with filename should work:

<img src="file:///C:/Users/91860/Desktop/snow.jpg" alt="Snow" style="width:100%;">
Stephen
  • 9,899
  • 16
  • 90
  • 137
1

You need to upload the image aswell, then link to the image on the server.

Kyle Hudson
  • 898
  • 1
  • 14
  • 26
1

If you're deploying a local website just for yourself or certain clients, you can get around this by running mklink /D MyImages "C:/MyImages" in the website root directory as an admin in cmd. Then in the html, do <img src="MyImages/whatever.jpg"> and the symbolic link established by mklink will connect the relative src link with the link on your C drive. It solved this issue for me, so it may help others who come to this question.

(Obviously this won't work for public websites since you can't run cmd commands on people's computers easily)

takanuva15
  • 1,286
  • 1
  • 15
  • 27
1

I have tried a lot of techniques and finally found one in C# side and JS Side. You cannot give a physical path to src attribute but you can give the base64 string as a src to Img tag. Lets look into the below C# code example.

<asp:Image ID="imgEvid" src="#" runat="server" Height="99px"/>

C# code

 if (File.Exists(filepath)
                            {
                                byte[] imageArray = System.IO.File.ReadAllBytes(filepath);
                                string base64ImageRepresentation = Convert.ToBase64String(imageArray);
                                var val = $"data: image/png; base64,{base64ImageRepresentation}";
                                imgEvid.Attributes.Add("src", val);
                            }

Hope this will help

Naveed Khan
  • 338
  • 4
  • 16
0

what about having the image be something selected by the user? Use a input:file tag and then after they select the image, show it on the clientside webpage? That is doable for most things. Right now i am trying to get it working for IE, but as with all microsoft products, it is a cluster fork().

Fallenreaper
  • 10,222
  • 12
  • 66
  • 129
0
background-image: url(${localImage});

If you want to add a file as background to your website locally.

double-beep
  • 5,031
  • 17
  • 33
  • 41