xyyd-fatfox/src/utils/upload.ts

41 lines
1.1 KiB
TypeScript
Raw Normal View History

2024-09-09 17:53:07 +08:00
import { ossBase, ossKeyUrl } from './../config'
import OSS from 'ali-oss'
import { v4 as uuid } from 'uuid'
export default async function upload(file: File, root: string) {
const config = await fetch(ossKeyUrl, {
method: 'POST',
headers: {
Authorization:
'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2NjlkZjA3Y2RhMjkyZTNiZTc0OGM5MmMifQ.9k9-C_Im2r2fONfT6rdAZDxapkqtwGtiVBSen59JDXY'
}
}).then(
(res) =>
res.json() as Promise<{
region: string
accessKeyId: string
accessKeySecret: string
securityToken: string
bucket: string
path: string
}>
)
const ext = file.name.split('.').pop()
const path = `${config.path}/${root}/${uuid()}.${ext}`
const client = new OSS({
region: config.region,
accessKeyId: config.accessKeyId,
accessKeySecret: config.accessKeySecret,
stsToken: config.securityToken,
bucket: config.bucket
})
console.log(path)
const { name } = await client.put(path, file, {
mime: file.type,
headers: {
'Content-Type': file.type
}
})
console.log(name)
return ossBase + '/' + name
}