Reubencf's picture
Fix: Use Hugging Face persistent /data directory for file storage
822cbdd
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 }
)
}
}