ai-bot/app/_ui/ImageUpload.tsx

83 lines
1.9 KiB
TypeScript

import { UploadOutlined } from "@ant-design/icons"
import { Button, Input, Space } from "antd"
import { useRef, useState } from "react"
import uploadOss from "../_lib/upload"
export default function ImageUpload(props: {
accept: string
width?: number
height?: number
value?: string
background?: string
hiddenCover?: boolean
onChange?: (val: string) => void
}) {
const inputRef = useRef<HTMLInputElement>(null)
const [loading, setLoading] = useState(false)
const handleFile = async (file: File) => {
setLoading(true)
try {
const url = await uploadOss(file, "aibot")
setLoading(false)
if (url) {
props.onChange?.(url)
}
} catch (e) {
setLoading(false)
}
}
return (
<>
{
!props?.hiddenCover
&&
<div
className="bg-center bg-no-repeat bg-contain rounded-lg shadow-lg flex items-center"
style={{
width: props.width || 240 + "px",
height: props.height || 120 + "px",
backgroundImage: `url('${props.value}')`,
backgroundColor: props.background || "rgba(0,0,0,0.2)",
}}
/>
}
<Space className={!props?.hiddenCover ? "mt-2" : ""}>
<Input value={props.value} onChange={(e) => {
props.onChange?.(e.target.value)
}}></Input>
<Button
loading={loading}
disabled={loading}
icon={<UploadOutlined />}
onClick={() => {
inputRef.current?.click()
}}
>
</Button>
</Space>
<input
type="file"
accept={props.accept}
ref={inputRef}
style={{
display: "none",
}}
onChange={(e) => {
const file = e.target.files?.[0]
e.target.value = ""
if (!file) return
handleFile(file)
}}
/>
</>
)
}