initiation librodrome
This commit is contained in:
37
server/api/admin/media/upload.post.ts
Normal file
37
server/api/admin/media/upload.post.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { writeFile, mkdir } from 'node:fs/promises'
|
||||
import { join, dirname } from 'node:path'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const formData = await readMultipartFormData(event)
|
||||
|
||||
if (!formData || formData.length === 0) {
|
||||
throw createError({ statusCode: 400, statusMessage: 'No files provided' })
|
||||
}
|
||||
|
||||
const publicDir = join(process.cwd(), 'public')
|
||||
const uploaded: string[] = []
|
||||
|
||||
for (const file of formData) {
|
||||
if (!file.filename || !file.data) continue
|
||||
|
||||
// Sanitize filename
|
||||
const safeName = file.filename.replace(/[^a-zA-Z0-9._-]/g, '_')
|
||||
|
||||
// Determine subdirectory from content type
|
||||
let subdir = 'uploads'
|
||||
const type = file.type ?? ''
|
||||
if (type.startsWith('image/')) subdir = 'images'
|
||||
else if (type.startsWith('audio/')) subdir = 'audio'
|
||||
else if (type === 'application/pdf') subdir = 'pdf'
|
||||
|
||||
const targetDir = join(publicDir, subdir)
|
||||
await mkdir(targetDir, { recursive: true })
|
||||
|
||||
const targetPath = join(targetDir, safeName)
|
||||
await writeFile(targetPath, file.data)
|
||||
|
||||
uploaded.push(`/${subdir}/${safeName}`)
|
||||
}
|
||||
|
||||
return { ok: true, files: uploaded }
|
||||
})
|
||||
Reference in New Issue
Block a user