-
-
Notifications
You must be signed in to change notification settings - Fork 30
[SDK] Image Upload
⚠️ Note: In 99% of cases, you want to use the useImageUpload
hook instead of the function version. The hook does the same thing but does not require you to pass the frameId
as a parameter.
This is the function version of the useImageUpload
hook, which means it doesn't have access to the Context, so it requires frameId
to be passed as a parameter. Usually, you'll want to use the useImageUpload
hook instead of the function version.
To upload an image, use the uploadImage
function and pass it the current frameId
, the contentType
and one of either base64String
(string)or buffer
(Buffer). It returns a promise that resolves to the fileName
and filePath
of the uploaded image.
The fileName
contains only the file name, including the extension, but not the full path. The filePath
contains the full path including the file name.
To display any uploaded image in an <img>
element or otherwise, concatenate the filePath
with the base process.env.NEXT_PUBLIC_CDN_HOST
to get the full URL.
import { useFrameConfig, useFrameId } from '@/lib/hooks'
import { uploadImage } from '@/lib/upload'
import { useEffect, useState } from 'react'
import type { Config } from '.'
export default function Inspector() {
const frameId = useFrameId()
const [config, updateConfig] = useFrameConfig<Config>()
const [imageName, setImageName] = useState('')
const [imagePath, setImagePath] = useState('')
return (
<div className="h-full flex flex-col gap-10">
<Input
accept="image/png, image/jpeg"
type="file"
onChange={async (e) => {
const userFile = e.target.files[0]
// initialize a file reader
const reader = new FileReader()
reader.readAsDataURL(userFile)
// get the base64 string representation
const base64String = (await new Promise((resolve) => {
reader.onload = () => {
const base64String = (
reader.result as string
).split(',')[1]
resolve(base64String)
}
})) as string
const contentType = userFile.type as
| 'image/png'
| 'image/jpeg'
const { fileName, filePath } = await uploadImage({
frameId: frameId,
base64String: base64String,
// if you want to upload a buffer instead of a base64 string
// buffer: myBuffer,
contentType: contentType
})
setImageName(fileName)
setImagePath(filePath)
}}
className="sr-only"
/>
{imageName && (
<img src={`https://cdn.frametra.in/frames/${frameId}/${imageName}`} />
)}
{imagePath && (
<img src={`https://cdn.frametra.in/${imagePath}`} />
)}
</div>
)
}