Angular-cli: Assets/Images not being served...

Created on 2 Mar 2018  路  44Comments  路  Source: angular/angular-cli

Versions

Angular CLI: 1.6.6
Node: 6.9.4
OS: win32 x64
Angular: 5.2.2
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router
@angular/cli: 1.6.6
@angular-devkit/build-optimizer: 0.0.42
@angular-devkit/core: 0.0.29
@angular-devkit/schematics: 0.0.52
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.9.6
@schematics/angular: 0.1.17
typescript: 2.5.3
webpack: 3.10.0

Repro steps

  1. add any image to /src/assets/images/
  2. reference image in HTML
  3. ng serve

    Observed behavior

image is not found
Request URL:http://localhost:4200/assets/images/logo.png
Request Method:GET
Status Code:404 Not Found

I have made sure that my angular-cli.json lists the assets folder...
image
Assets folder directly under src directory
image
HTML is typical

  <img src="./assets/images/logo.png"/>

Image is 404
image

Here is a minimal example...
https://github.com/smatthews1999/testng

devkibuild-angular

Most helpful comment

@aajmot I thought I should downgrade to 1.6.3 to overcome, Luckily found out a solution without downgrading, just remove all the symbols, brackets for all your folders starting from particular drive.
If u'r project is in E drive follow below
change this location

E:Dataproject - 1Angular(learning)app

to

E:Dataproject1Angularlearningapp

U will be able to see the loaded assets folder to the browser under sources tab in chrome developer tools

All 44 comments

I am having the same problem :/ I tried with the latest version and still doesn't work!

@smatthews1999 <img src="assets/images/ic_launcher.png"> It ran successfully for me.

It's after the packs are updated npm update
I can attach an icon

Need verify package versions

@smatthews1999 Try increasing the dimensions of the image in paint. I had an image in the path src/assets/Library/Images with dimensions 60 x 45 which did not load and an image with dimensions 225 x 225 which loaded successfully. Hope this helps !

if img convert to base64? then his break in file system.
Need verify css file

@smatthews1999 Have u found out a solution to u'r problem, I face the same problem while I was trying to render the image, It was giving me the same error as 404 Not Found. I have tried alt+click on the path of the image and it took me to the image on my vscode. But don't know why it's not able find the image on browser. Anyone please help !!!
Here is the version of angular cli and browser-platform
angular cli version

I am having the same issue,

Angular CLI: 6.0.8
Node: 8.11.2
OS: win32 x64
Angular: 6.0.4

@aajmot I thought I should downgrade to 1.6.3 to overcome, Luckily found out a solution without downgrading, just remove all the symbols, brackets for all your folders starting from particular drive.
If u'r project is in E drive follow below
change this location

E:Dataproject - 1Angular(learning)app

to

E:Dataproject1Angularlearningapp

U will be able to see the loaded assets folder to the browser under sources tab in chrome developer tools

the way i have done it is by creating assets folder in each component and inside it created an images and then placed the images that are need for that particular component, then importing the images from same component folder and it works

Can you try using the binding..

I tried the solution @avinashdv proposed and it worked. You need to make sure all the folders of your project's path have no : [] or "." in them my project was [BYCK][1.0] when I turned it into BYCK_10 it worked .

I am still having this issues. There are no special characters in my file path except "_", image is inside assets/img folder. I see it in the dist for prod build, but local dev server isn't serving it up.

Figured it out, apparently file names are case sensitive.

@PTC-JoshuaMatthews
Glad it helped

Try increasing the width and height of the image. It worked for me

Assets not loading after --prod build and then deployed to firebase? all styles font etc work, just not images?? assets folder only?? everything works fine on local server. All other projects deployed successfully in the past? this project is giving me grief! ng v 6.1.0 I have no errors???

@alvics I'm getting same issues here. can't load images of assets folders properly when deployed to firebase. on local machine works perfects. Trying to solve this, but i think ill have to back to prior cli version.

@paulimfavarato let me know how you go? I still trying! no luck, try some tests?? It use to be easy not sure what there doing with the CLI? :(

@alvics @paulimfavarato I can confirm I'm experiencing this too, and I dug up a bit of info on what's happening.

  1. Interestingly, on deploying the same app to any other static host like Surge, it works fine, so I determined it must be specifically a Firebase problem.
  2. I tried dropping an image in the root of my dist/ folder, and accessing it via [my-site-name].firebaseapp.com/assets/images/test.jpg. This worked fine! So it's just stuff in assets/images that isn't working.
  3. So then I tried directly accessing [my-site-name].firebaseapp.com/assets/images/test.jpg... and got redirected to my root index.html. I suspect this is the source of our problem.
  4. I tried turning off Firebase's redirects completely, but then it still redirected me to my root index.html! For paths which don't exist, I correctly get a 404, but for paths which do match existing files under assets/, I instead get the redirect. I do not understand why this occurs.

In any case, check if your Firebase deployments are exhibiting the same behavior. I can probably whip up an example repo if it's useful.

I am experiencing the same issue. I deploy my static website to firebase but any file inside public folder like images or CSS are displayed. I remove the redirection from firebase.json file and now any non-existing file is redirected to 404.html file. But, why static files are not deployed to firebase?

This is my configuration file:

{
  "hosting": {
    "public": "public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ]
  },
  "functions": {
    "predeploy": [
      "npm --prefix \"%$RESOURCE_DIR%\" run lint"
    ],
    "source": "functions"
  }
}

my folder structures is like this:

capture

Hi !

Same issue here when trying to ng build --prod on my server. My path contains no special characters, my cases are respected.

Working with

angular-cli : 6.2.3, Node : 8.9, Angular : 5.2.3

My href in my index html is : <base href="./">

I do have my assets folder appearing in the dist folder, but still the path is not working. I guess that the path when built is not corresponding to what i'm thinking, even if it fits perfectly

<img src="assets/images/IconSyderCompact.png">
Note that in my case my img tag is not in index.html but in a another html file within index.html, dunno if it can modify anything

In angular.json :

    "Crapo": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist",
            "index": "src/index.html",
            "main": "src/main.ts",
            "tsConfig": "src/tsconfig.app.json",
            "polyfills": "src/polyfills.ts",
            "assets": [
              "src/assets"
            ],

The only solution i found is to convert the image to base64. I would like very much to understand the issue here.

@Linpter is the file in question within the dist directory after the build? If so, then the CLI is doing everything as expected. If not, please open a new issue with details of the project encountering the problem.

in developer tools, we can see why our pictures are broken... It is because the path to your images is wrong.
All of your files are downloaded from for example localhost/AngularApp/ so your images are on localhost/AngularApp/assets .... but unfortunately, the browser looks for them on localhost/assets and that's why it doesn't get anything.

solution:

save img URL in this format: './assets/fries.png'

maybe I meet same problem. When I use svg tag shows images before build everthing seems fine. Howerver, after ng build the cannot show image . What I fix:
change:
<image xlink:href="../assets/images/BW80.png" height="80px" width="80px" x="840" y="90"></image>
to:
<image xlink:href="./assets/images/BW80.png" height="80px" width="80px" x="840" y="90"></image>
And my server will auto add http:xxx.xxx.xx/altual
I am not sure fit for everyone , try this and feedback to me

this is worked for me --> src="assets/images/logo.png"

Thanks.

src="assets/info.png" use this in place of src="/assets/info.png" It will work for everyone

By default angular-cli.json takes "src/assets" path. In my case the following path worked for me-this.errorMessageImage="assets/images/cross-icon.png";
But do take care of base href="/" in index.html file, this href attach "/" before every image path.
Hope it helps!

@AasthaWadhwa01
If you used assets for background css. Then assets deleted.
example:

.logo_my-bg {
  background: url(/assets/logo_my_site.png);
}

After doesn't work that is

<img src="/assets/logo_my_site.png" />

This is because, assets are converted base64. And will be included in the bundel.style.css
Used tag "IMG" only for api img

<img src="/myApi/user_img/123456" />

Replace you tag img on div

<div class="logo_my-bg" />

If you're trying to get an image from url, eg to a background through stylesheet (or similar), try use sanitizer:

import { DomSanitizer, SafeStyle } from '@angular/platform-browser';

...

  /**
   * Get picture from url
   * @param url string
   */
  getPictureUrl(url: string): SafeStyle {
    const style = `url('${url}')`;
    return this.sanitizer.bypassSecurityTrustStyle(style);
  }

<div [style.background-image]="getPictureUrl('https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png')"></div>

In a simple way, considering that your images are in assets directory, then:

<img src="assets/image1.png" />

nothing works using latest angular 7

ng build --aot false --buildOptimizer=false --prod --deploy-url "https://mydomain.com:9999/api/"



...

project name is api

prefix in angular.json "api"

    "projects": {
        "api": {
            "root": "",
            "sourceRoot": "/src",
            "projectType": "application",
            "prefix": "api",
            "schematics": {
<img src='assets/logo-pp.png' / >

your assertion that referencing from assets is wrong its broken

root paths especially off of docroot are NOT properly being spelled out thru and within bundles

more info...
tsconfig

        "baseUrl": "./src",
        "paths": {
            "@app/*": [
                "app/*"
            ],
            "@env/*": [
                "environments/*"
            ],
            "@assets/*": [
                "assets/*"
            ],
            "@ext/*": [
                "ext/*"
            ]
        },

here is a piece of angular.json

            "architect": {
                "build": {
                    "builder": "@angular-builders/custom-webpack:browser",
                    "options": {
                        "customWebpackConfig": {
                            "path": "extra-webpack.config.js"
                        },
                        "outputPath": "dist/api",
                        "index": "src/index.html",
                        "main": "src/main.ts",
                        "polyfills": "src/polyfills.ts",
                        "tsConfig": "src/tsconfig.app.json",
                        "assets": [
                            {
                                "glob": "favicon.ico",
                                "input": "src",
                                "output": "/"
                            },
                            {
                                "glob": "**/*",
                                "input": "src/assets",
                                "output": "/assets"
                            }
                        ],

I dont get this...
the i18n files beneath assets/* wont load either

unless I rig up a pointer in environments.ts

i18nPrefix: '/api',

does this need to be done for assets images on templates too ?

This is end end result in the markup

<img _ngcontent-c9="" src="assets/logo-pp.png">

so my solution was to hardwire the element in the template

<img src='/api/assets/logo-pp.png' />

not good

does anyone know a solution for production building?

Im having to hardwire with an appRootPrefix in environment.ts in order to serve up internationalized language files beneath my assets folder and various sporadic app images off the template or from within the component fed to the template.

export const environment = {
    appRootPrefix: '/api',
}

and then

    ngOnInit() {
        this.image.nativeElement.setAttribute(
            'src',
            `${environment.appRootPrefix}/assets/logo-pp.png`
        )
    }

or

        this.image.nativeElement.setAttribute(
            'src',
            `${environment.appRootPrefix}/assets/avatar.png`
        )

or

export function HttpLoaderFactory(http: HttpClient) {
    return new TranslateHttpLoader(
        http,
        `${environment.appRootPrefix}/assets/i18n/`,
        '.json'
    )
}

not good for production

C:\apache-tomcat-9.0.14\api>ng --version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / ? \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 7.2.3
Node: 8.12.0
OS: win32 x64
Angular: 7.2.2
... animations, cdk, common, compiler, compiler-cli, core, forms
... http, language-service, material, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.12.3
@angular-devkit/build-angular     0.12.3
@angular-devkit/build-optimizer   0.12.3
@angular-devkit/build-webpack     0.12.3
@angular-devkit/core              7.2.3
@angular-devkit/schematics        7.2.3
@angular/cli                      7.2.3
@angular/flex-layout              7.0.0-beta.19
@ngtools/webpack                  7.2.3
@schematics/angular               7.2.3
@schematics/update                0.12.3
rxjs                              6.3.3
typescript                        3.2.4
webpack                           4.28.4


C:\apache-tomcat-9.0.14\api>

my app project is called 'api'

regardless of my production configuration states

"baseHref": "/api",

or

"baseHref": "/api/",

am seeing same result... cannot serve image

the resulting index.html beneath dist/api always has
<base href="/api/">

so after build takes place the APP gets moved to
C:\apache-tomcat-9.0.14\webapps\ROOT\api

relative to C:apache-tomcat-9.0.14webappsROOT

there are several scenarios but the latest one failing for me is

<a href='https://www.paypal.com/cgi-bin/'>
    <img src='assets/logo-pp.png' #image />
</a>

<!--<img [src]='image' #image /> this one failed previously -->

here is the resulting markup

<img _ngcontent-c9="" src="/assets/logo-pp.png">

from this template

<a href='https://www.paypal.com/cgi-bin/webscr' target='_blank'>
    <!--<img [src]='image' #image />-->
    <img src='assets/logo-pp.png' #image />
    <img src='https://www.paypalobjects.com/en_US/i/btn/btn_subscribe_LG.gif' />
</a>

the rest of my app works fine serving up en.json language files but with the hardwired prefix

so something is up with whats being put within the bundles

I cannot open them up and see

logo-pp.png:1 GET https://www.mysite.com/assets/logo-pp.png 404

it may be SSL has something to do with this ?

@nhhockeyplayer
Your assets img used in css.
Check css.
After doesn't work that is
<img _ngcontent-c9="" src="/assets/logo-pp.png">

Try increasing the width and height of the image. It worked for me

You really did not get this...

I have the same problem:

angular.json

"assets": [
              {
                "glob": "**/*",
                "input": "src/assets",
                "output": "assets"
              }
            ],

And my error:

http://localhost:8008/assets/images/icon.png 404 (Not Found)

Our Team encounters the same issue today.
We are building the "--prod" version.

We have seen that the image name is changing to something like "imagename.hash.png" if it is used in CSS.
So that's why it is showing error while rendering.

once we have set the src="assets/imageName.png" works like a charm.

Also one more point we have noted that the background images we have set in CSS file itself. So in this case angular automatically converts the image name to "imagename.hash.png" in CSS class as well. that's why this is working.

I am also getting the same error ... and on looking under networks tab found the following difference between the type of my two separate .png images. Both images have the same size and I am adding them in the html file as

<img class="img-thumbnail rounded mr-3 anim-zoomin" style="width:40%;height:auto" src="assets/images/image.png" alt="Generic placeholder image">

image

Does anyone have an idea of what does this mean? or how could I resolve it ?

I've run into the same issue I think and posted on stack here: angular-8-assets-not-loading and was told to update this thread (hope that's ok :-) ).

Basically check the full path, I had parenthesis in mine and that stopped the assets from working.

  • myTestApp2 => works
  • 'my test' => works
  • 'my test(12)' => doesn't work

Hope it helps someone !

For anyone still having this issue, this was fixed it for me:

Open your tsconfig.json file (It is in the top level of your workspace directory).

Change this:
"outDir": "./dist/out-tsc",

to this:
"outDir": "./dist"

This answer was gotten from https://stackoverflow.com/a/56206651 where you can see the rest of it.

This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

_This action has been performed automatically by a bot._

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jmurphzyo picture jmurphzyo  路  3Comments

naveedahmed1 picture naveedahmed1  路  3Comments

NCC1701M picture NCC1701M  路  3Comments

rwillmer picture rwillmer  路  3Comments

brtnshrdr picture brtnshrdr  路  3Comments