Angular 6 Failing To Load Images From Assets

2020-06-03 01:19发布

For some reason I can't get my images to show in my app. This is the error, tests and class:

The error: GET http://localhost:4200/assets/image.png 404 (Not Found)

<img class="logo" src="../../assets/image.png">
<img class="logo" src="../assets/image.png">
<img class="logo" src="assets/image.png">
//None of these work

.logo {
    height: 100px;
    width: auto;
    padding: 10px;
    display: block;
    margin: 0 auto;
}

Any idea why this is not working? My image.png is in my assets folder which is located at src/assets/image.png.

Update:

So we did a test. We copied all the node modules and the project files to another pc and there the images loaded correctly. So I assume the problem lies outside the angular project it self.

12条回答
手持菜刀,她持情操
2楼-- · 2020-06-03 01:51

src="assets/image.png" should work without issue. Have you restarted your build since you added in the image?

查看更多
干净又极端
3楼-- · 2020-06-03 01:53

Following other tutorials on the web, I created a src\app\assets\images folder and put my image there. However, my app already had an assets folder in src\assets. There are two fixes to this.

Either:

  1. Put my image in the existing src\assets folder and reference as <img src="src\assets\my-image.png"/> or
  2. Add src\app\assets to my angular.json assets declaration and reference as was my original intention of src\app\assets\images\my-image.png.
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2020-06-03 01:55

I had same issue, this has turned out to be a case sensitive issue on the path.

In my case image folder under assets was in capital I on the image folder. /assets/Images/angularconnect-shield.png

so check, your image path and make sure it is exactly matching with.

查看更多
beautiful°
5楼-- · 2020-06-03 01:56

it's because of you don't have permission to access file.

simple way in windows Move your project from drive C: to other drive. it's work fine.

Good luck.

查看更多
Summer. ? 凉城
6楼-- · 2020-06-03 01:56

If it's due to case-sensitivity in URLs hosted by 'ng serve', there is an option to disable that. 'ng serve' uses webpack-dev-server which uses http-proxy-middleware. You can write a custom middleware script which corrects the url-case to match the file-case (it only affects the server response, the browser still sees the original url).

An example of how to code that is posted here: https://github.com/webpack/webpack-dev-server/issues/578#issuecomment-569121500

查看更多
在下西门庆
7楼-- · 2020-06-03 01:57

So the problem is that the angular project was lying in a location where it was causing an error. In my case it was lying in a bitbucket repository. I am not sure if that is the reason for the error though.

Try moving the whole angular project to a different location. That solved it for me :)

@Rak2018's solution is a good workaround if you would like to use that instead

查看更多
登录 后发表回答