Html local img src

Fixing img src local file paths

Getting issues with img src not loading local file paths? Check these tips to find how to fix them!

Jan 9, 2023 | Read time 8 minutes

🔔 Table of contents

Introduction

A common annoyance that comes up when doing web design locally is loading up local files. For example in the below code, we are trying to load a file located in our C: temp folder — C:/temp/mylocalfile.jpg

 Now this does not work because, C:/ is not a protocol. The src attribute only accepts protocols. Now we can see that this will work with older Microsoft browsers such as IE9, but will fail with modern browsers like Chrome, Firefox, etc!

To fix img src to load local file paths, we need to use the file protocol

Using the file protocol

If we want the tag to load up a file within our own computer/machine, we need to use the file protocol (referenced here: https://datatracker.ietf.org/doc/html/rfc8089)

Читайте также:  Sign Up

The file protocol follows the syntax:

Keep in mind that we do not need to specify the host part. If there is not host part in the file URI, then it just resolves to localhost.

However, even when we do not set the host value, we still need to specify the extra forward slash file:///.

Img src local path on mac or linux systems

Using the file protocol is a bit different on mac (OSX) or linux systems versus on Windows. Consider the following img tag trying to load a photo.png file:

 Notice that we are using the ~ tilde (~User). On mac (OSX) or linux systems, this is a common way to expand our path from the home path. However, the file protocol does not recognize things like the tilde character ( ~ ) so you will need to fill it out manually.

So you would need file:///home/User/photo.png (on most Unixes), and use file:///Users/User/photo.png (on Mac OS X)

There are also other things to check if the img src is not loading aswell.

Follow the below suggestions:

Check 1 — Validate the syntax

The syntax for loading a image from a source is by . Now src only accepts valid URLs with accepted protocols. A protocol is a few letters, then a colon and two slashes.

For example, HTTP:// , and FTP:// are valid.

Going to back to our orignal code that was not loading the images correctly, , the browser does not recognize that URL, since it is thinking to load http://c:/

When using the file protocol, we need to make sure that we have the correct slashes. file:///.. should be generally safe to use. On windows it is more forgiving and allows double slashes.

Additionally, if your filename contains spaces or special characters we need to encode it.

As an example, lets say we want to reference the file C:/temp/my local file.jpg — notice the spaces. We need to encode it — replacing the whitespace to %20 .

Note: Why three slashes in file:/// ?

Using the three slashes file:///C:/etc is just a short hand. It is the same as file://localhost/C:/etc

Check 2 — Verify the file extension

One issue that can trip some people up is that the file names can be case insensitive. This will be based on the serve that is hosting your website.

With most Unix based servers (Linux, or OSX), the files are case sensitive. While on Windows servers, they are case insensitive.

As an example, if you are hosting with Apache on Ubuntu it does care about the casing on your filename or path.

As for under Windows it is correct to assume that aBc.html and abc.html are exactly the same file.

In the example below, lets say we have image called photo.png, the second line will not load the image due to the all caps PNG extension

Check 3 — Using relative paths

One way to get around issues around local file paths not loading with img src is to use relative paths. However, when we chooe to go down this path, we need to make sure that we are using the correct syntax to load relative files.

  • / — This means the root directory
  • ../ — This means going up on directory
  • ./ — This means the current directory (if you are working off the current directory, you may not need this — just use the file name)
  • ../../ — This means going up two directories

Lets say we got the following basic folder structure:

Check 4 — Clear cache and check for errors

A common reason why you cant see your PNG src changes is that the browser is caching the image assets.

What I usually do is to open up dev tools (Option + ⌘ + J (on macOS), or Shift + CTRL + J (on Windows/Linux)) and tick the “Disable Cache (while DevTools is open)”

image on how to open DevTools and open its settings. This way we can ensure that our code is using the most up to date image.

image on how to open DevTools and open its settings

Additionally, you can check if your image file (eg PNG or JPG) is loading correctly by inspecting the console in DevTools. Usually if it is not showing, we can see a 404 error:

image of how file is not loading shows in DevTools

Tip: Use a development server like Live Server in VS Code!

If you are coding with VS Code, then using the Live Server extension is a must. When you are just coding locally without a local server running, references to images can get a bit confusing.

For example, if you use the root directory / — this could mean your actual C:/ root folder instead of the current folder!

Live server can be downloaded here: https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer

Summary

In this post, I went over some steps you can take to fix issues with loading img src from the local file path. Firstly, we need to make sure that we are using the file protocol ( file:/// ) and that our syntax is correct.

We need to verify that the image path is correct and that we are considering case sensitivity. For windows systems, file paths are case sensitive, while linux or mac OSX are case insensitive.

An alternative to use the file protocol is using relative paths based on your project’s root folder.

Additionally, if the previous steps are not working, we can check to see if the browser is caching the error — in this case we should open up the browser settings (DevTools) to clear the cache!

👋 About the Author

G’day! I am Kentaro a software engineer based in Australia. I have been creating design-centered software for the last 10 years both professionally and as a passion.

My aim to share what I have learnt with you! (and to help me remember 😅)

👉 See Also 👈

Источник

Как добавить в HTML картинку из папки

Вы видели какие-нибудь сайты без изображений? Да, может нам и попадутся несколько, но в наши дни это редкость. Давайте узнаем, как можно добавлять изображения в HTML-документы.

Современный интернет в значительной степени полагается на изображения, относящиеся к содержанию сайта, поскольку это помогает улучшить внешний вид сайта и помогает читателям лучше понять контент.

Веб-сайт может содержать несколько изображений, которые часто сгруппированы в подкаталогах и папках. Таким образом, важно узнать, как включить изображение в файл HTML из папки.

HTML тег

Вы можете включить изображение в HTML с помощью HTML-тега .

img src="flowers.jpg" alt="A Flower Bouquet"/> 

Тег загружает изображение и помещает его на веб-страницу. У него есть 2 важных атрибута:

  • src — указывает исходное расположение, в котором браузер будет искать файл изображения. Получив файл изображения, он загружает изображение на веб-страницу. Мы можем использовать URL-адрес (унифицированный указатель ресурсов) для отображения изображения с другого веб-сайта.
  • alt — задает текст, который нам нужно отобразить, если изображение недоступно или если система не может загрузить изображение. Этот текст также помогает посетителям с ограниченными возможностями, использующих программу чтения с экрана.

Как установить источник изображения в HTML

Давайте узнаем немного больше о том, как указать источник изображения.

Базовый случай — указать имя файла изображения, которое вы хотите поместить в HTML-документ.

img src="flowers.jpg" alt="A Flower Bouquet"/> 

Браузер будет искать изображение в той же папке, в которую вы поместили HTML-документ.

Если изображение находится в папке или подкаталоге, вам также необходимо включить его в источник.

img src="/images/flowers.jpg" alt="A Flower Bouquet"/> 

После того, как вы добавили строку /images к источнику, браузер будет искать в нем изображение flowers.jpg вместо текущего каталога.

Как добавить изображение в HTML из удаленного места

Изображения, которые вы используете на своих HTML-страницах, не обязательно должны располагаться рядом с ними. Вы можете легко добавлять изображения из удаленных мест (с других веб-сайтов или файловых хранилищ) с помощью URL-адреса.

img src="https://learn.coderslang.com/js-test-8.png" alt="JavaScript test"/> 

Как использовать “.” или “..” в качестве источника изображения в HTML

Вы можете указать браузеру искать изображение в текущем каталоге, используя одну точку . в атрибуте src .

img src= "./flowers.jpg" alt="A Flower Bouquet"/> 

Или, если вы хотите переместиться на один каталог вверх, вы должны используете две точки .. , чтобы браузер начал поиск изображения на один уровень выше текущего каталога.

img src="../otherImages/flowers.jpg" alt="A Flower Bouquet"/> 

Источник

Оцените статью