Skip to content

k.site.images ​

Upload, query by URL or folder, update metadata/bytes, and delete site images

Execution ContextPrerequisitesTypical Use
KScript API / Server scriptsCurrent site context; uploading requires image byte arrayUpload images via addImage() with auto route creation, query, and update metadata

Quick Start ​

Upload an image from k.request.files to the site media library (automatically measures dimensions and registers its route):

js
k.api.post(() => {
    const file = k.request.files[0]
    const uploaded = k.site.images.addImage(
        "/uploads/" + file.fileName,
        file.bytes,
        "Uploaded image"
    )
    return {
        id: String(uploaded.id),
        url: uploaded.url,
        width: uploaded.width,
        height: uploaded.height,
        previewUrl: uploaded.previewUrl
    }
})

Quick Reference ​

Method / PropertyDescriptionReturns
addImage(path, data, alt?)Uploads image bytes to a path, measures dimensions, and registers a routeMediaStorageFileModel
all()Returns all Image records in the site (column-only metadata; omits alt and contentBytes)Image[]
get(nameOrId)Retrieves an image by GUID id (filename lookup returns null)Image | null
getByUrl(url)Retrieves an image by its registered route URLImage | null
getByFolder(folder)Lists images under a folder path (column-only metadata; iterate with for...of)Image[]
add(image)Adds an image record (throws without bytes; prefer addImage())void
update(image)Persists metadata updates (must pass a full object from get(id) or getByUrl(url))void
updateBinary(nameOrId, binary)Replaces image bytes and updates sizevoid
delete(nameOrId)Deletes an image by id along with its routevoid
getLogs(nameOrId)Returns change history entries for the imageChangeLog[] | null
getByLog(logId)Restores an image snapshot by log entry IDImage | null

Related APIs and Console Tools

API / GuidePurpose
k.site.imagesUpload (addImage), query, update metadata/binary, and delete site images
k.site.filesManage general repository files (CmsFile)
Media Library (CMS Console)Browse and manage images in the Kooboo console

Runtime Notes

  • Use addImage() to upload: calling add({ name: "..." }) without binary bytes throws "Value cannot be null. (Parameter 'buffer')".
  • all() and getByFolder() return column-only metadata: these methods only populate indexed columns (id, name, width, height, size, lastModified) and do not load alt or contentBytes. Always fetch the full Image via get(id) or getByUrl(url) before reading alt or calling update(image); passing a partial object from all() or getByFolder() directly to update(image) will silently wipe out the stored binary bytes (contentBytes = null) in the database.
  • Random GUID IDs: Image assigns a random GUID id rather than hashing the filename, so get(name) returns null. Look up images via uploaded.id, getByUrl(url), or all().
  • Compare IDs as strings: GUID properties returned across calls should be compared with String(a.id) === String(b.id).
  • getByFolder() returns an iterable list: Array.isArray(...) is false at runtime; iterate over results using for...of.

Detailed Methods ​

addImage() ​

Uploads raw image bytes to a site path, registers the route, measures dimensions, and optionally stores alt text.

ParameterTypeRequiredDescription
pathstringYesTarget site URL path (for example, "/images/banner.png")
datanumber[]YesImage byte array (for example, file.bytes from an uploaded request file)
altstringNoOptional alt text

Returns: MediaStorageFileModel including id, url, width, height, size, previewUrl, and downloadUrl.

js
k.api.post(() => {
    const file = k.request.files[0]
    const uploaded = k.site.images.addImage(
        "/uploads/" + file.fileName,
        file.bytes,
        "Banner"
    )
    return { id: String(uploaded.id), url: uploaded.url }
})

all() / get() / getByUrl() / getByFolder() ​

List site images or look them up by GUID id, registered route URL, or folder path.

MethodParametersReturnsDescription
all()NoneImage[]Returns all images in the site repository (column-only metadata; alt and contentBytes are not loaded)
get(nameOrId)nameOrId: stringImage | nullRetrieves a full Image by its GUID id (filename lookup returns null)
getByUrl(url)url: stringImage | nullRetrieves a full Image by its registered route URL (for example, "/uploads/logo.png")
getByFolder(folder)folder: stringImage[]Lists images under the specified folder path (column-only metadata; alt and contentBytes are not loaded; iterate with for...of)

Returns: Image[] or Image | null

js
k.api.get(() => {
    const byUrl = k.site.images.getByUrl("/uploads/logo.png")
    const inRoot = k.site.images.getByFolder("/")
    const rootIds = []
    for (const img of inRoot) {
        rootIds.push(String(img.id))
    }
    return {
        foundByUrl: !!byUrl,
        totalImages: k.site.images.all().length,
        rootIds
    }
})

update() / updateBinary() / delete() ​

Update image metadata, replace stored bytes, or delete an image and its route by id.

MethodParametersReturnsDescription
update(image)image: ImagevoidPersists image metadata changes (such as alt); must pass a full object from get(id) or getByUrl(url), never a partial item from all() / getByFolder()
updateBinary(nameOrId, binary)nameOrId: string, binary: number[]voidReplaces the stored bytes of an existing image and updates size
delete(nameOrId)nameOrId: stringvoidDeletes the image by id along with its route

Returns: void

js
k.api.post(() => {
    const img = k.site.images.get(k.request.form.id)
    if (!img) return { found: false }

    img.alt = "Updated alt text"
    k.site.images.update(img)

    const logs = k.site.images.getLogs(img.id)
    const snapshot = logs && logs.length ? k.site.images.getByLog(logs[0].logId) : null
    return {
        alt: k.site.images.get(img.id)?.alt,
        logCount: logs ? logs.length : 0,
        snapshotMatched: !!snapshot && String(snapshot.id) === String(img.id)
    }
})

getLogs() / getByLog() ​

Inspect image change history and restore snapshots by log entry ID.

MethodParametersReturnsDescription
getLogs(nameOrId)nameOrId: stringChangeLog[] | nullReturns change history entries for the image, or null if none exist
getByLog(logId)logId: numberImage | nullRestores an image snapshot by log entry ID

Returns: ChangeLog[] | null or Image | null

TypeScript Definitions ​

Show full TypeScript definitions
ts
interface ImageRepository {
  addImage(path: string, data: number[], alt?: string): MediaStorageFileModel;
  all(): Image[];
  get(nameOrId: string): Image | null;
  getByUrl(url: string): Image | null;
  getByFolder(folder: string): Image[];
  add(image: Partial<Image>): void;
  update(image: Image): void;
  updateBinary(nameOrId: string, binary: number[]): void;
  delete(nameOrId: string): void;
  getLogs(nameOrId: string): ChangeLog[] | null;
  getByLog(logId: number): Image | null;
}

interface MediaStorageFileModel {
  id: string;
  key: string;
  url: string;
  name: string;
  size: number;
  folder: string;
  previewUrl: string;
  downloadUrl: string;
  mimeType: string;
  width: number;
  height: number;
  isImage: boolean;
  type: string;
  alt: string;
  lastModified: Date;
}

interface Image {
  id: string;
  name: string;
  extension: string;
  alt: string;
  width: number;
  height: number;
  size: number;
  isSvg: boolean;
  creationDate: Date;
  lastModified: Date;
}