4. Photos

Upload from the photo picker, keep the id, show the URL.

3 MIN READView Markdown ↗

A photo is two calls: upload the file, then send a message that points to it. Every generated client has uploadFile(uri) for the first; you write the second.

The backend#

Add files to the import. Message gets a photoUrl, and MessageRow the photo column:

TypeScript
import { ApiError, caller, event, files, online } from 'arkapi/server'

export interface Message {
  id: number
  name: string
  text: string
  photoUrl: string | null
  mine: boolean
}

interface MessageRow {
  id: number
  name: string
  text: string
  photo: string | null
  mine: number
}

Select the photo in getMessages and turn its id into a URL:

TypeScript
export function getMessages(): Message[] {
  const rows = db.query<MessageRow, [string]>(`
    select m.id, coalesce(p.name, 'Announcement') as name, m.text, m.photo, m.device = ? as mine
    from messages m left join people p on p.device = m.device
    order by m.id desc limit 100`).all(caller().deviceId)
  return rows.reverse().map((row) => ({
    id: row.id, name: row.name, text: row.text, mine: row.mine === 1,
    photoUrl: row.photo === null ? null : files.url(row.photo),
  }))
}

And add sendPhoto below sendMessage:

TypeScript
export function sendPhoto(fileId: string): void {
  if (!files.list().some((file) => file.id === fileId)) throw new ApiError('NOT_FOUND', 'Upload the photo first')
  save(me(), '', fileId)
}

Store the file id in your database, not the URL: files.url builds the URL for wherever the backend runs, on your computer now and on the hosted service later. Files are at most 10 MB, survive deploys, and anyone with the URL can open them.

The screen#

Import the photo picker, and add sendPhoto and uploadFile to the client imports:

ArkTS
import { AsyncValue, Listening, LiveValue } from 'arkapi'
import { photoAccessHelper } from '@kit.MediaLibraryKit'
import { countOnline, getMessages, getName, Message, onTyping, sendMessage, sendPhoto, setName, setTyping, Typing, uploadFile } from './chat.api'

Add a + button at the start of the input row:

ArkTS
    Row({ space: 8 }) {
      Button('+')
        .fontColor('#FFFFFF')
        .backgroundColor('#2A2A33')
        .enabled(!this.sending.loading)
        .onClick(() => { this.sending.run(this.pickPhoto()) })

And the method that picks, uploads and sends, above send:

ArkTS
  async pickPhoto(): Promise<void> {
    try {
      const options = new photoAccessHelper.PhotoSelectOptions()
      options.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE
      options.maxSelectNumber = 1
      const picked = await new photoAccessHelper.PhotoViewPicker().select(options)
      if (picked.photoUris.length > 0) {
        const photo = await uploadFile(picked.photoUris[0])
        await sendPhoto(photo.id)
      }
    } catch (error) {
      throw error as Error
    }
  }

The try that only rethrows is there for the ArkTS compiler, which warns about picker calls outside one. The error still reaches this.sending.

pickPhoto returns a promise like any call, so the same AsyncValue that drives Send also disables both buttons during the upload.

Finally, in bubble, show the photo instead of the text bubble when there is one:

ArkTS
      Text(message.name).fontSize(11).fontColor('#8A8A99')
      if (message.photoUrl !== null) {
        Image(message.photoUrl).width(180).borderRadius(14)
      } else {
        Text(message.text)
          .fontSize(15)
          .fontColor('#FFFFFF')
          .padding({ left: 12, right: 12, top: 8, bottom: 8 })
          .borderRadius(14)
          .backgroundColor(message.mine ? '#4F6BF5' : '#2A2A33')
      }

Try it#

Send a photo with +. sendPhoto is a mutation, so the photo reaches every screen the same way a text message does.

Next: announcements from outside.

Tab to navigate results · Enter to open · Esc to close