0.6.2.0
This commit is contained in:
+32
-7
@@ -20,15 +20,21 @@ export async function POST(req: NextRequest) {
|
||||
return NextResponse.json({ error: '没有文件' }, { status: 400 })
|
||||
}
|
||||
|
||||
// 验证文件类型
|
||||
if (!file.type.startsWith('image/')) {
|
||||
return NextResponse.json({ error: '只能上传图片文件' }, { status: 400 })
|
||||
// 验证文件类型(支持图片和视频)
|
||||
const isImage = file.type.startsWith('image/')
|
||||
const isVideo = file.type.startsWith('video/')
|
||||
if (!isImage && !isVideo) {
|
||||
return NextResponse.json({ error: '只能上传图片或视频文件' }, { status: 400 })
|
||||
}
|
||||
|
||||
// 验证文件大小(限制为 5MB)
|
||||
const maxSize = 5 * 1024 * 1024 // 5MB
|
||||
// 验证文件大小(图片限制 5MB,视频限制 100MB)
|
||||
const maxImageSize = 5 * 1024 * 1024 // 5MB
|
||||
const maxVideoSize = 100 * 1024 * 1024 // 100MB
|
||||
const maxSize = isVideo ? maxVideoSize : maxImageSize
|
||||
if (file.size > maxSize) {
|
||||
return NextResponse.json({ error: '文件大小不能超过 5MB' }, { status: 400 })
|
||||
return NextResponse.json({
|
||||
error: isVideo ? '视频文件大小不能超过 100MB' : '图片文件大小不能超过 5MB'
|
||||
}, { status: 400 })
|
||||
}
|
||||
|
||||
// 读取文件内容
|
||||
@@ -44,7 +50,26 @@ export async function POST(req: NextRequest) {
|
||||
// 生成唯一文件名
|
||||
const timestamp = Date.now()
|
||||
const randomStr = Math.random().toString(36).substring(2, 8)
|
||||
const ext = file.name.split('.').pop()
|
||||
|
||||
// 从文件名或 MIME 类型获取扩展名
|
||||
let ext = file.name.split('.').pop()?.toLowerCase()
|
||||
if (!ext || ext === file.name) {
|
||||
// 如果没有扩展名,从 MIME 类型推断
|
||||
const mimeToExt: Record<string, string> = {
|
||||
'image/jpeg': 'jpg',
|
||||
'image/png': 'png',
|
||||
'image/gif': 'gif',
|
||||
'image/webp': 'webp',
|
||||
'image/svg+xml': 'svg',
|
||||
'video/mp4': 'mp4',
|
||||
'video/webm': 'webm',
|
||||
'video/ogg': 'ogg',
|
||||
'video/quicktime': 'mov',
|
||||
'video/x-msvideo': 'avi',
|
||||
'video/x-matroska': 'mkv',
|
||||
}
|
||||
ext = mimeToExt[file.type] || 'bin'
|
||||
}
|
||||
const fileName = `${timestamp}-${randomStr}.${ext}`
|
||||
|
||||
// 保存文件
|
||||
|
||||
Reference in New Issue
Block a user