Ошибка 404 img html

here’s a confusing thing. first look at the hierarchy of my folders and etc. and see that I have my image, «cribbage.png» under the images folder. I am trying to access this image with the following code in index.html:`

<!doctype html>
<html lang = "en">
    <head>

    </head>
    <body>
        <h1>Hello World! </h1>
        <img src= "images/cribbage.png" width= "970" height="224"/>
        <div id = "future"></div>
        <form id = "form" id = "chat_form">
            <input id = "username" type="text">
            <input type = "submit" value="Play">
        </form>
        <script src = "/jquery/dist/jquery.js"></script>
        <script src = "/socket.io/socket.io.js">
    </body>
</html>

and yet, when loading the website I get
the following and the image is replaced with the broken image icon.

What exactly is wrong here?

asked Mar 12, 2018 at 13:32

Max Blankenship's user avatar

1

I have noticed that some web frameworks don’t allow you to have your images or videos anywhere you want. For example, while looking for the solution for this problem, I remembered that Flask (the framework I was using) does not render any images or videos that are not in the «static» folder.

I don’t know if other frameworks have something like this, but if you think you have everything in order, you should take this into consideration.

answered Jul 19, 2022 at 19:50

Mario's user avatar

MarioMario

212 bronze badges

The images field is not on the same folder as index.html. Meaning your path should get out of the node_modules folder and then get in the images folder.

you should use / (to get out of the node folder) images and then/ (to get in the images folder )cribbage.png

so ../images/cribbage.png

answered Mar 12, 2018 at 13:39

Martin Kariuki's user avatar

2

check on the folder that the name of the image is in lowercase because it is case sensitive

answered May 2, 2019 at 3:50

José Caicedo's user avatar

try:

<img src= "/images/cribbage.png" width= "970" height="224"/>

answered Mar 12, 2018 at 13:36

connor.gregson's user avatar

7

Is the images folder in the right place?
Make sure you can access to the folder from the browser.

answered Aug 20, 2019 at 6:44

grape100's user avatar

grape100grape100

3254 silver badges11 bronze badges

<form id="form1" runat="server">
<div>
<img src="../../../Images/Gallery/error2.jpg"  width= "500" height="300" CssStyle="text-align:center"/>
</div>
</form>
</asp:Panel>

answered Nov 20, 2019 at 7:11

Irfan Pathan's user avatar

1

In my case, I had too many folders e.i img/images, so I moved all my images from images folder to img folder, and all my images show successfully

answered Nov 22, 2020 at 14:05

Kurisani Chauke's user avatar

you should try this
<img src= "./images/cribbage.png" width= "970" height="224"/>

answered Nov 22, 2020 at 14:14

ibrahim s's user avatar

ibrahim sibrahim s

2971 silver badge7 bronze badges

Tonia_

1 / 1 / 0

Регистрация: 09.03.2018

Сообщений: 30

1

01.05.2020, 13:34. Показов 6701. Ответов 4

Метки express, html, img (Все метки)


Студворк — интернет-сервис помощи студентам

Я смотрела похожу тему на форуме (Не хочет загружать img в HTML документе), но у меня немного по другому. Помогите разобраться в чем ошибка. Почему картинка не загружается?

about.ejs

HTML5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
<head>
    <title>Открытка</title>
    <meta charset="utf-8" />
</head>
<body>
    <div >
         // .....
        <p><img src="/images/pic.png" alt="картинка"></p>
        // .....
    </div>
</body>
</html>

Сервер (app.js):

Javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const express = require("express");
const bodyParser = require("body-parser");
  
const app = express();
var path = require('path');
 
const urlencodedParser = bodyParser.urlencoded({extended: false});
app.set('view engine','ejs');
 
// app.use('/images',express.static('public')); // не работает
 
app.post("/register", urlencodedParser, function (request, response) {
    if(!request.body) return response.sendStatus(400);
    console.log(request.body);
    response.render('about',{date: request.body});
});
  
app.get("/", function(request, response){
    response.render('register');
});
 
app.listen(3000);

Изображения

 



0



2 / 2 / 0

Регистрация: 01.05.2020

Сообщений: 13

02.05.2020, 11:44

2

В строке № 10 html файла перед images убери слеш



1



1 / 1 / 0

Регистрация: 09.03.2018

Сообщений: 30

02.05.2020, 12:27

 [ТС]

3

Не загружается(
Failed to load resource: the server responded with a status of 404 (Not Found)



0



shvyrevvg

1786 / 1036 / 445

Регистрация: 12.05.2016

Сообщений: 2,550

02.05.2020, 19:14

4

Лучший ответ Сообщение было отмечено Tonia_ как решение

Решение

Tonia_,

Javascript
1
app.use(express.static(__dirname + '/images'));
HTML5
1
<img src="/pic.png" alt="картинка">



1



1 / 1 / 0

Регистрация: 09.03.2018

Сообщений: 30

03.05.2020, 05:09

 [ТС]

5

Работает!)
Спасибо



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

03.05.2020, 05:09

5

It’s possible for a request for an image to receive a 404 response that has an image Content-Type with valid image data attached, to be displayed as a placeholder. Currently, img elements are required to display this placeholder data (per 4.8.4.3 Processing Model):

Whether the image is fetched successfully or not (e.g. whether the response status was an ok status) must be ignored when determining the image’s type and whether it is a valid image.

What’s less clear is how this should apply to the case of picture elements with a list of sources, when one of those sources fails with a placeholder 404 image.

The status quo

My understanding of the spec is that if a source fails with a 404, regardless of whether placeholder data is received, the browser is supposed to try the next source in the list:

  • The media resource selection algorithm, step 9, case children, sub-step 8 requires that the source‘s target resource be fetched using the resource fetch algorithm.
  • The resource fetch algorithm, step 4, case remote, sub-step 8, sub-sub-step 4 requires that the network request used to fetch the resource be verified. Verification fails if the internal response’s status code is not 200 or 206.
  • Some of the steps around there link to the HTTP fetch standard; I dug around and didn’t find anything in that standard that would result in the browser «lying» about a 404 request with placeholder data not being a 404. Looking at the HTTP-network fetch steps, it seems like the server’s original status code is applied to the response directly, at least for codes outside the [100, 199] range.
  • If the resource fetch algorithm fails, then the media resource selection algorithm, step 9, case children will not be aborted at sub-step 8, and so will continue to the next steps, which involve moving onto the next source (if any) and trying that one.

It seems that the spec-compliant behavior would be:

  • If a source fails with a 404, try the next source, regardless of whether the failing source had placeholder image data attached to the 404 response.
  • If all sources fail, and the img also fails, then use only any placeholder image data attached to the img‘s 404 response. If the img 404 response did not contain placeholder data, then display a broken image (i.e. no placeholder data from any source will be used).

Current browser behavior

If Chromium and Mozilla Firefox encounter a source that 404s with placeholder content, they will display that placeholder content, instead of making any attempt to try the next source(s) in the list. Additionally, neither browser makes any attempt to try more than the first source with a supported MIME type. Consider the code below:

<!doctype html>
<html>
   <body>
      <picture>
         <!-- <source srcset="https://example.com/nonexistent.png" type="image/jpeg" /> -->
         <source srcset="https://i.ytimg.com/vi/asdf/nonexistent.jpg" type="image/jpeg" />
         <source srcset="https://i.ytimg.com/vi/dQw4w9WgXcQ/maxresdefault.jpg" type="image/jpeg" />
         <source srcset="https://i.ytimg.com/vi/dQw4w9WgXcQ/sddefault.jpg" type="image/jpeg" />
         <img set="https://i.ytimg.com/vi/dQw4w9WgXcQ/default.jpg" />
      </picture>
   </body>
</html>

We are here trying to display the YouTube thumbnail for Rick Astley’s «Never Gonna Give You Up.» There are multiple possible URLs for a YouTube thumbnail, and not all such URLs are available for every video; additionally, if any image request to the YouTube thumbnail server fails, the server returns a 404 response with a 120x90px image/jpeg placeholder attached. This placeholder is what the above code displays in Firefox and Chromium. If we uncomment the obviously broken example.com URL, then Firefox and Chromium just display a broken image; watching the network requests allows us to see that they never attempt to request anything else after failing to load nonexistent.png.

It seems, then, like a key portion of the spec for picture and source elements is completely unimplemented in every major browser.

So I guess my questions are…

  1. Should the spec be amended to match existing browser behavior? It seems like it’d be far more useful if web browsers actually implemented the «try each source until one works» part of the spec instead.

  2. Suppose that web browsers were to ignore 404 placeholder data on a source: if a source 404s, the browser tries the next source or, if none remain, the img, instead of just displaying any placeholder data that was sent along with the 404.

    If all sources fail, the img also fails, and one or more sources had placeholder data, then should the spec be amended to have the browser display one of those sources’ placeholders? Should the browser prefer the earliest source in the list that had a placeholder? Should the browser prefer the img placeholder, if one was received, over all source placeholders?

    I don’t know terribly much about how network requests are done under the hood, but I’d imagine that if browsers can use the earliest placeholder in the list, then they don’t have to actually bother to fully load the placeholders for any failing source elements after that one.

  3. …Am I even interpreting these parts of the spec properly to begin with?

Решение ошибки 404 при загрузке изображений в тег img

Введение

Во время разработки при загрузке изображения с помощью <img src = «/img/yys.png» /> будет ошибка 404, что означает, что изображение не найдено.

           ПодарокбудуРешение Резюмируется следующим образом:

Во-вторых, решение

Если изображение не найдено или 404, атрибут onerror тега <img /> будет активирован для отображения изображения в нем.


    1. Прямое написание пути:

    <img src = "img/yys.png" onerror = "javascript:this.src = 'img/default.png'" />


         2. Метод привязки событий:

    <img src = "img/yys.png" onerror = "javascript:getImage('img/default.png')" />

    function getImage(imgUrl) {
  
        var img = event.srcElement;

        img.src = imgUrl;

    }

    

  ------------------------------------- ↓↓↓↓↓ -------------------------------------

         Специальное примечание: если изображение по умолчанию (img / default.png) не существует, как его решить:
    
    <img src = "img/yys.png" onerror = "this.onerror = ''; this.src = 'img/default.png'" />

  ------------------------------------- ↑↑↑↑↑ -------------------------------------
    

                       Now ~ ~ ~Я закончил писать здесь, если вам посчастливилось помочь вам, пожалуйста, не забудьте следовать за мной и стать свидетелем нашего совместного роста

вот такая запутанная вещь. сначала посмотрите на иерархия моих папок и т. д. и увидите, что у меня есть мое изображение «cribbage.png» в папке с изображениями. Я пытаюсь получить доступ к этому изображению с помощью следующего кода в index.html: `

<!doctype html>
<html lang = "en">
    <head>

    </head>
    <body>
        <h1>Hello World! </h1>
        <img src= "images/cribbage.png" width= "970" height = "224"/>
        <div id = "future"></div>
        <form id = "form" id = "chat_form">
            <input id = "username" type = "text">
            <input type = "submit" value = "Play">
        </form>
        <script src = "/jquery/dist/jquery.js"></script>
        <script src = "/socket.io/socket.io.js">
    </body>
</html>

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

Что именно здесь не так?

ваш URL-адрес указывает на localhost/images/yourimagename.jpg, тогда как ваша структура папок — localhost/crib/images/yourimagename.jpg


— kevinniel

12.03.2018 14:35

Toor - Ангулярный шаблон для бронирования путешествий

Раскрытие чувствительных данных

Раскрытие чувствительных данных

Все внешние компоненты, рассмотренные здесь до сих пор, взаимодействуют с клиентской стороной. Однако, если они подвергаются атаке, они не…

Разница между тегами Br и Wbr в HTML 5

Разница между тегами Br и Wbr в HTML 5

В целом, оба тега <br> и <wbr> имеют свои уникальные цели и функциональные возможности, и их использование зависит от конкретных требований к дизайну…

HTML И VS CODE Для Веб-разработки

HTML И VS CODE Для Веб-разработки

Прежде чем начать кодировать html в «VS CODE», мы должны сначала создать папку и назвать ее x.html, здесь я принимаю x как имя файла, который мы…

Как использовать WAI-ARIA

Как использовать WAI-ARIA

В моем текущем новом проекте почти все компоненты не учитывают веб-доступность. Моя нынешняя компания — это стартап, поэтому они не заботились о…

Статическая веб-страница, созданная с помощью CSS и HTML - до и не до.


Ответы
7

пытаться:

<img src= "/images/cribbage.png" width= "970" height = "224"/>

Это не работает, та же ошибка 404, а изображение все еще не найдено.


— Max Blankenship

12.03.2018 14:45

в вашей ссылке «иерархия моих папок и т. д.» вы пытаетесь получить изображение в файле «index.html», расположенном в папке «/ node_modules»? если да, то сделайте ../images/cribbage.png


— connor.gregson

12.03.2018 14:48

если это так, и это решает вашу проблему, я бы предложил переместить папку изображений в папку / node_modules и код, который я вам сначала дал :)


— connor.gregson

12.03.2018 14:50

На самом деле это не так, и проблема сохраняется. Я все равно попробовал сделать ../images/cribbage.png, но это все равно не сработало.


— Max Blankenship

12.03.2018 14:54

где находится html-файл, в который вы пытаетесь загрузить изображение?


— connor.gregson

12.03.2018 14:55

Пожалуйста, дополните


— Vinay Prajapati

12.03.2018 19:27

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


— connor.gregson

12.03.2018 19:34

Поле изображений находится не в той же папке, что и index.html. Это означает, что ваш путь должен выйти из папки node_modules, а затем попасть в папку изображений.

вы должны использовать / (чтобы выйти из папки узла) images, а затем / (чтобы попасть в папку изображений) cribbage.png

итак ../images/cribbage.png

Спасибо за объяснение, но я все еще таинственным образом получаю ту же ошибку 404.


— Max Blankenship

12.03.2018 14:46

Попробуйте <img src = «../ images / cribbage.png»>


— Martin Kariuki

12.03.2018 15:03

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

Папка изображений находится в нужном месте?
Убедитесь, что у вас есть доступ к папке из браузера.

В моем случае у меня было слишком много папок e.i img / изображений, поэтому я переместил все свои изображения из папки изображений в папку img, и все мои изображения успешно отображаются

ты должен попробовать это
<img src= "./images/cribbage.png" width= "970" height = "224"/>

поместите полную ссылку URL.
например: имя вашего сервера test.com
http://test.com/imagefoldername/imagename

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


— jad

24.01.2021 12:42

Другие вопросы по теме

Понравилась статья? Поделить с друзьями:
  • Ошибка 404 github pages
  • Ошибка 404 freepik
  • Ошибка 404 flask
  • Ошибка 404 file not found
  • Ошибка 404 faceit