File size: 1,784 Bytes
c7fbc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { writeFile, mkdir } from "fs/promises";
import { NextRequest, NextResponse } from "next/server";
import path from "path";
import { v4 as uuidv4 } from "uuid";

export async function POST(req: NextRequest) {
    const formData = await req.formData();
    const files = formData.getAll("file") as File[];

    if (!files || files.length === 0) {
        return NextResponse.json({ error: "No files provided" }, { status: 400 });
    }

    const urls: string[] = [];
    let type = "IMAGE";

    // Check types
    const hasVideo = files.some(f => f.type.startsWith("video/"));
    const hasImage = files.some(f => f.type.startsWith("image/"));

    if (files.length > 1) {
        type = "CAROUSEL";
    } else if (hasVideo) {
        type = "VIDEO";
    }

    // Ensure upload dir
    const uploadDir = path.join(process.cwd(), "public", "uploads");
    await mkdir(uploadDir, { recursive: true });

    for (const file of files) {
        const buffer = Buffer.from(await file.arrayBuffer());
        const ext = path.extname(file.name) || (file.type.startsWith("image") ? ".jpg" : ".mp4");
        const filename = `${uuidv4()}${ext}`;
        const filepath = path.join(uploadDir, filename);

        await writeFile(filepath, buffer);

        // In production we'd upload to S3/Cloudinary and return that URL.
        // For local dev, we serve from public/uploads.
        // Note: Graph API requires PUBLICLY ACCESSIBLE URLs.
        // If running on localhost, Instagram server CANNOT fetch this.
        // CRITICAL: We need ngrok or similar for Instagram Graph API to fetch media.
        // Or we upload to a public bucket. 
        // I will note this limitation.

        urls.push(`/uploads/${filename}`);
    }

    return NextResponse.json({ urls, type });
}