Skip to content

Instantly share code, notes, and snippets.

@FHoxhaDev
Created March 3, 2024 08:59
Show Gist options
  • Save FHoxhaDev/59e2dc2b1cc134b6d064b96573a51145 to your computer and use it in GitHub Desktop.
Save FHoxhaDev/59e2dc2b1cc134b6d064b96573a51145 to your computer and use it in GitHub Desktop.
APIUploadCall
import { NextRequest, NextResponse } from 'next/server'; // To handle the request and response
const fs = require("fs").promises; // To save the file temporarily
import { v4 as uuidv4 } from 'uuid'; // To generate a unique filename
import PDFParser from 'pdf2json'; // To parse the pdf
import { File } from 'buffer';
import { join } from "path";
import { tmpdir } from "os";
export async function POST(req: NextRequest) {
console.log('Incoming request...');
const formData: FormData = await req.formData();
const uploadedFiles = formData.getAll('filepond');
let fileName = '';
let parsedText = '';
if (uploadedFiles && uploadedFiles.length > 0) {
const uploadedFile = uploadedFiles[1];
console.log('Uploaded file:', uploadedFile);
// Check if uploadedFile is of type File
if (uploadedFile instanceof File) {
console.log('Uploaded file is of type File.');
// Generate a unique filename
const fileName = uuidv4();
console.log('Generated file name:', fileName);
// Get the system's temporary directory
const tmpDir = tmpdir();
console.log('Temporary directory:', tmpDir);
// Generate the path to the temporary file
const tempFilePath = join(tmpDir, `${fileName}.pdf`);
console.log('Temporary file path:', tempFilePath);
// Convert ArrayBuffer to Buffer
const fileBuffer = Buffer.from(await uploadedFile.arrayBuffer());
console.log('Converted ArrayBuffer to Buffer.');
// Save the buffer as a file
await fs.writeFile(tempFilePath, fileBuffer);
console.log('File saved successfully.');
// Parse the pdf using pdf2json.
const pdfParser = new (PDFParser as any)(null, 1);
await new Promise<void>((resolve, reject) => {
// See pdf2json docs for more info on how the below works.
pdfParser.on('pdfParser_dataError', (errData: any) =>
console.log(errData.parserError)
);
pdfParser.on('pdfParser_dataReady', () => {
console.log('PDF parsing complete.');
console.log('Raw text content:', (pdfParser as any).getRawTextContent());
parsedText = (pdfParser as any).getRawTextContent();
resolve();
});
pdfParser.loadPDF(tempFilePath);
});
} else {
console.log('Uploaded file is not in the expected format.');
}
} else {
console.log('No files found.');
}
console.log('Preparing response...');
const response = new NextResponse(parsedText);
response.headers.set('FileName', fileName);
console.log('Response prepared.');
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment