Newer Version Available
Use Images Uploaded as Asset Files
Asset files are the modern alternative to static resources. Asset files are ideal for
images that are used throughout your components and apps—for example, user interface elements like
icons—or otherwise aren’t related to a specific record.
Referencing an image stored in an Asset file is straightforward, and fully documented. We present only a simple example here. See Access Content Asset Files the Lightning Web Component Developer Guide for complete details.
The critical elements of an offline-ready implementation are:
- Access the URL of the asset using the @salesforce/contentAssetUrl module.
- Provide the image URL via a getter function.
- Use the getter function for the src attribute of an img tag in your HTML template.
1// imageFromAssetFile.js
2import { LightningElement } from 'lwc';
3import ASSET_IMG from '@salesforce/contentAssetUrl/avatars-light-mode';
4import ARCHIVE_IMG from '@salesforce/contentAssetUrl/branding-images';
5
6export default class ImageFromAssetFile extends LightningElement {
7 get assetUrl() {
8 return ASSET_IMG;
9 }
10
11 get assetArchiveUrl() {
12 return ARCHIVE_IMG + '&pathinarchive=images/logo-large.png';
13 }
14}With the image URL provided by the getter functions in the preceding component JavaScript, referencing the images in the HTML template is just like referencing any image in HTML. Use it in the src attribute of an HTML img tag.
1<!-- imageFromAssetFile.html -->
2<template>
3 <lightning-card>
4 Display an image directly from an Asset file {assetUrl}
5 </lightning-card>
6
7 <template if:true={assetUrl}>
8 <img src={assetUrl}/>
9 </template>
10
11 <lightning-card>
12 Display an image from an archive Asset file {archUrl}
13 </lightning-card>
14
15 <template if:true={assetArchiveUrl}>
16 <img src={assetArchiveUrl}/>
17 </template>
18
19</template>