File size: 2,775 Bytes
8af739b
 
 
 
822cbdd
 
 
 
8af739b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { NextRequest, NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'

// Use /data for Hugging Face persistent storage, fallback to local for development
const DATA_DIR = process.env.NODE_ENV === 'production' && fs.existsSync('/data')
  ? '/data'
  : path.join(process.cwd(), 'data')
const DOCS_DIR = path.join(DATA_DIR, 'documents')
const MAX_FILE_SIZE = 50 * 1024 * 1024 // 50MB

export async function POST(request: NextRequest) {
  try {
    const formData = await request.formData()
    const file = formData.get('file') as File
    const folderPath = formData.get('folder') as string || ''

    if (!file) {
      return NextResponse.json({ error: 'No file provided' }, { status: 400 })
    }

    // Check file size
    if (file.size > MAX_FILE_SIZE) {
      return NextResponse.json(
        { error: `File size exceeds ${MAX_FILE_SIZE / 1024 / 1024}MB limit` },
        { status: 400 }
      )
    }

    // Sanitize filename
    const fileName = file.name.replace(/[^a-zA-Z0-9._-]/g, '_')
    const uploadDir = path.join(DOCS_DIR, folderPath)
    const filePath = path.join(uploadDir, fileName)

    // Security check
    if (!filePath.startsWith(DOCS_DIR)) {
      return NextResponse.json({ error: 'Invalid upload path' }, { status: 400 })
    }

    // Create directory if it doesn't exist
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true })
    }

    // Check if file already exists
    if (fs.existsSync(filePath)) {
      // Add timestamp to filename if it exists
      const timestamp = Date.now()
      const ext = path.extname(fileName)
      const baseName = path.basename(fileName, ext)
      const newFileName = `${baseName}_${timestamp}${ext}`
      const newFilePath = path.join(uploadDir, newFileName)

      // Convert file to buffer and save
      const bytes = await file.arrayBuffer()
      const buffer = Buffer.from(bytes)
      fs.writeFileSync(newFilePath, buffer)

      return NextResponse.json({
        success: true,
        message: 'File uploaded (renamed due to conflict)',
        fileName: newFileName,
        path: path.join(folderPath, newFileName).replace(/\\/g, '/'),
        size: file.size
      })
    }

    // Convert file to buffer and save
    const bytes = await file.arrayBuffer()
    const buffer = Buffer.from(bytes)
    fs.writeFileSync(filePath, buffer)

    return NextResponse.json({
      success: true,
      message: 'File uploaded successfully',
      fileName: fileName,
      path: path.join(folderPath, fileName).replace(/\\/g, '/'),
      size: file.size
    })
  } catch (error) {
    console.error('Error uploading file:', error)
    return NextResponse.json(
      { error: 'Failed to upload file' },
      { status: 500 }
    )
  }
}