Implement File Upload in Next.js for DALL-E API Integration
16 views
If you want to allow users to upload a reference image in a Next.js application before generating variations using the DALL-E API, you'll need to set up a file upload feature. Here’s how you can implement that:
Step 1: Update the API Route to Handle File Uploads
Modify your API route to accept an image file uploaded by the user. You can utilize a library like formidable for handling file uploads in Next.js.
First, install formidable:
npm install formidable
Now, update your pages/api/generateImage.js:
// pages/api/generateImage.js
import formidable from 'formidable';
import fs from 'fs';
import path from 'path';
import axios from 'axios';
// Allow Next.js to handle form data
export const config = {
api: {
bodyParser: false,
},
};
const handler = async (req, res) => {
if (req.method === 'POST') {
const form = new formidable.IncomingForm();
form.parse(req, async (err, fields, files) => {
if (err) {
return res.status(500).json({ error: 'Failed to parse form data' });
}
const { prompt } = fields;
const imageFile = files.image;
// Read the uploaded image
const image = fs.readFileSync(imageFile.filepath);
const formData = new FormData();
formData.append('image', image, {
filename: imageFile.originalFilename,
contentType: imageFile.mimetype,
});
formData.append('prompt', prompt);
try {
const response = await axios.post('https://api.openai.com/v1/images/generations', formData, {
headers: {
'Authorization': `Bearer YOUR_API_KEY`, // Replace with your OpenAI API Key
...formData.getHeaders(),
},
});
const generatedImageUrl = response.data.data[0].url;
res.status(200).json({ url: generatedImageUrl });
} catch (error) {
console.error('Error generating image variation:', error.response ? error.response.data : error.message);
res.status(500).json({ error: 'Failed to generate image' });
}
});
} else {
res.setHeader('Allow', ['POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
};
export default handler;
Step 2: Create a Frontend Component for File Upload
Now, create a simple form on the frontend that allows users to upload an image and input a prompt. Here’s an example component:
// components/GenerateImage.js
import { useState } from 'react';
const GenerateImage = () => {
const [prompt, setPrompt] = useState('');
const [imageFile, setImageFile] = useState(null);
const [imageUrl, setImageUrl] = useState('');
const handleFileChange = (e) => {
setImageFile(e.target.files[0]);
};
const handleSubmit = async (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('image', imageFile);
formData.append('prompt', prompt);
const response = await fetch('/api/generateImage', {
method: 'POST',
body: formData,
});
const data = await response.json();
if (response.ok) {
setImageUrl(data.url);
} else {
console.error(data.error);
}
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="file"
accept="image/*"
onChange={handleFileChange}
required
/>
<textarea
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
placeholder="Describe your image..."
required
/>
<button type="submit">Generate Image</button>
</form>
{imageUrl && <img src={imageUrl} alt="Generated" />}
</div>
);
};
export default GenerateImage;
Step 3: Use the Component in a Page
Finally, use the GenerateImage component in one of your pages, like pages/index.js:
// pages/index.js
import GenerateImage from '../components/GenerateImage';
export default function Home() {
return (
<div>
<h1>Image Variation Generator</h1>
<GenerateImage />
</div>
);
}
Important Notes:
- Be sure to replace
'YOUR_API_KEY'with your actual OpenAI API key in the API route. formidablehandles the file upload and parsing of the incoming form data.- Ensure you have proper error handling and user feedback in your production application for a better user experience.
- This example assumes a simple frontend structure; feel free to style it further as per your project needs.
- Handle different scenarios of file uploads (like file size limits, file type validation, etc.) as per your requirements.
- Consider security aspects related to file uploads (e.g., validate file types, limit file size) to prevent any potential vulnerabilities.