To create a UI for selecting a PDF file and uploading it to OpenAI in a Node.js environment, you'll need to set up a web server with HTML for file selection and a backend to handle the file upload. Express is a popular choice for the web server, and you can use Multer for handling file uploads in Express.
First, install the required packages with npm:
npm install express multer axios form-data
Now, let's set up the server and the file upload logic:
const express = require('express');
const multer = require('multer');
const axios = require('axios');
const FormData = require('form-data');
const app = express();
const port = 3000;
// Configure multer for file storage
const storage = multer.memoryStorage(); // Use memory storage, files will be accessible as buffer
const upload = multer({ storage: storage });
// Serve an HTML form at the root which allows PDF file selection
app.get('/', (req, res) => {
res.send(`
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="pdf" accept="application/pdf" required>
<button type="submit">Upload</button>
</form>
`);
});
// Route to handle the PDF file upload
app.post('/upload', upload.single('pdf'), async (req, res) => {
if (!req.file) {
return res.status(400).send('No file uploaded.');
}
try {
const formData = new FormData();
formData.append('file', req.file.buffer, req.file.originalname);
formData.append('purpose', 'assistants');
const response = await axios.post(
'https://api.openai.com/v1/files',
formData,
{
headers: {
'Authorization': `Bearer YOUR_OPENAI_API_KEY`,
...formData.getHeaders()
}
}
);
res.send(`File uploaded successfully: ${JSON.stringify(response.data)}`);
} catch (error) {
res.status(500).send(`Error uploading file: ${error}`);
}
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
Replace YOUR_OPENAI_API_KEY with your actual OpenAI API key. Now, run the server using:
node your_server_file.js
When you navigate to http://localhost:3000 in your browser, you will see a simple form that allows you to select a PDF file. Upon submission, the PDF file gets uploaded to the server, which in turn uploads it to OpenAI.
This code does not include error handling for the OpenAI response. You should implement proper error checking and handle any API limits or restrictions as needed.
Remember to treat your API keys securely. Do not commit them to version control, and consider using environment variables or a secrets management system to store them.
This example is for educational purposes and is a simple implementation. For production systems, consider implementing more robust file validation, error handling, content security policy (CSP), CSRF protection, and other security best practices.