Photos and files

Upload from the device, keep the id, show the URL.

2 MIN READView Markdown ↗

Every generated client has uploadFile(uri). Pass a local file URI, for example from the photo picker. It returns a FileRef with id and url.

TypeScript
import { photoAccessHelper } from '@kit.MediaLibraryKit'
import { sendPhoto, uploadFile } from './chat.api'

async function pickAndSend(): Promise<void> {
  const options = new photoAccessHelper.PhotoSelectOptions()
  options.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE // images only
  options.maxSelectNumber = 1
  try {
    const selected = await new photoAccessHelper.PhotoViewPicker().select(options)
    if (selected.photoUris.length === 0) return // the user cancelled
    const photo = await uploadFile(selected.photoUris[0]) // bytes go to file storage; photo = { id, url }
    await sendPhoto(photo.id)
  } catch (e) {
    console.error(`Photo not sent: ${e}`)
  }
}

Show it with Image(photo.url).

On the server#

The upload stores the bytes and nothing else. Your endpoint decides what the file belongs to:

TypeScript
import { files } from 'arkapi/server'

export async function sendPhoto(fileId: string): Promise<number> {
  await files.read(fileId) // NOT_FOUND if there is no such upload
  return savePhotoMessage(fileId, files.url(fileId))
}

files.write(data, type) stores bytes or text and returns an id, files.read(id) returns the bytes, files.list() returns ids and sizes, and files.remove(id) deletes a file.

Good to know#

  • Files are at most 10 MB, survive deploys, and are public to anyone with the URL.
  • Uploading and using a file are two calls. Store ids in your database, and check ownership before removing a file.
  • uploadFile is reserved; do not name an endpoint that.
Tab to navigate results · Enter to open · Esc to close