Why can't I do <img src="C:/localfile.jpg">?
Asked Answered
C

16

130

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?

Cannabin answered 3/11, 2010 at 19:11 Comment(5)
May I ask why you would want to do such a thing?Chickabiddy
@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.Exorbitant
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.Coastwise
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=""Coastwise
Just use a development webserver on your machine. It's easy nowadays since even PHP comes with one built in.Wyoming
K
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.

Kalmar answered 3/11, 2010 at 19:14 Comment(7)
still, flash manages to access anything the user selects, even in ChromeFettle
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.Cannabin
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.Kalmar
This paranoid security is only a disturbance. You CAN upload user files to the server with AJAX from a form with <input type=file> 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?Mulhouse
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.Mulhouse
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 @MulhouseKalmar
@javier that's exactly the point and the reason because flash had been deprecatedCarvajal
C
39

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

Cardinal answered 3/11, 2010 at 19:13 Comment(2)
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.Greenshank
file:///localfile.jpg is correect one for linuxCacophonous
E
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"/>

Epistasis answered 3/11, 2010 at 19:13 Comment(1)
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!Iasis
S
20

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

Scarlet answered 3/11, 2010 at 19:13 Comment(0)
U
8

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

Unfolded answered 5/10, 2016 at 15:12 Comment(0)
T
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>
Transom answered 2/4, 2018 at 11:39 Comment(3)
Chrome throws an error in console "Not allowed to load local resource".Saraann
@Saraann 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.Transom
@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...Crossruff
J
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".

Joeyjoffre answered 27/9, 2012 at 14:2 Comment(0)
L
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.

Linwoodlinz answered 3/11, 2010 at 19:14 Comment(3)
Unless you can. I haven't given much context in the question, I know :) But in this case we can actually know.Cannabin
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.Sundberg
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.Anarchism
C
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.

Calorimeter answered 3/11, 2010 at 19:48 Comment(0)
S
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">
Stringboard answered 8/12, 2015 at 12:45 Comment(2)
That Didnt work for me in chrome, but it does work in IE?Exurbanite
This will NOT WORK under Linux systems, but will work fine in Windows systems.Greenshank
A
2

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

<img src="file:///C:/Users/91860/Desktop/snow.jpg" alt="Snow" style="width:100%;">
Abbasid answered 10/8, 2020 at 11:9 Comment(1)
Take care: this trick will not work in Linux systems.Greenshank
D
1

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

Dorri answered 3/11, 2010 at 19:15 Comment(0)
A
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)

Albumen answered 2/2, 2018 at 20:28 Comment(0)
S
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

Schreib answered 16/7, 2020 at 10:16 Comment(0)
P
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().

Patent answered 25/6, 2012 at 15:43 Comment(0)
J
0
background-image: url(${localImage});

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

Jemie answered 10/1, 2023 at 13:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.