feat: 城中村租房平台 - 租客浏览、房东发布房源、图片上传
This commit is contained in:
53
app/api/upload/route.ts
Normal file
53
app/api/upload/route.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
|
||||
const UPLOAD_DIR = path.join(process.cwd(), 'public/uploads');
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const formData = await request.formData();
|
||||
const file = formData.get('file') as File | null;
|
||||
|
||||
if (!file) {
|
||||
return NextResponse.json({ error: '请选择图片' }, { status: 400 });
|
||||
}
|
||||
|
||||
const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
|
||||
if (!allowedTypes.includes(file.type)) {
|
||||
return NextResponse.json({ error: '仅支持 JPG、PNG、GIF、WebP 格式' }, { status: 400 });
|
||||
}
|
||||
|
||||
const ext = file.name.split('.').pop() || 'jpg';
|
||||
const filename = `${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`;
|
||||
const filepath = path.join(UPLOAD_DIR, filename);
|
||||
|
||||
const buffer = await file.arrayBuffer();
|
||||
await fs.writeFile(filepath, Buffer.from(buffer));
|
||||
|
||||
const url = `/uploads/${filename}`;
|
||||
return NextResponse.json({ url });
|
||||
} catch (error) {
|
||||
console.error('Upload error:', error);
|
||||
return NextResponse.json({ error: '上传失败' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const filename = searchParams.get('filename');
|
||||
|
||||
if (!filename) {
|
||||
return NextResponse.json({ error: '缺少文件名' }, { status: 400 });
|
||||
}
|
||||
|
||||
const filepath = path.join(UPLOAD_DIR, path.basename(filename));
|
||||
await fs.unlink(filepath);
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error('Delete error:', error);
|
||||
return NextResponse.json({ error: '删除失败' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user