Property add and cloudinary upload

This commit is contained in:
Brad Traversy
2024-07-11 07:49:45 -04:00
parent d8265eb88f
commit 0dc15b1a13
9 changed files with 70 additions and 7 deletions
+25 -5
View File
@@ -4,6 +4,7 @@ import Property from '@/models/Property';
import { getSessionUser } from '@/utils/getSessionUser';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import cloudinary from '@/config/cloudinary';
async function addProperty(formData) {
await connectDB();
@@ -18,10 +19,7 @@ async function addProperty(formData) {
// Access all values for amenities and images
const amenities = formData.getAll('amenities');
const images = formData
.getAll('images')
.filter((image) => image.name !== '') // Filter out empty names
.map((image) => image.name); // Extract only the names
const images = formData.getAll('images').filter((image) => image.name !== '');
// Create the propertyData object with embedded seller_info
const propertyData = {
@@ -48,10 +46,32 @@ async function addProperty(formData) {
email: formData.get('seller_info.email'),
phone: formData.get('seller_info.phone'),
},
images,
owner: userId,
};
const imageUrls = [];
for (const imageFile of images) {
const imageBuffer = await imageFile.arrayBuffer();
const imageArray = Array.from(new Uint8Array(imageBuffer));
const imageData = Buffer.from(imageArray);
// Convert the image data to base64
const imageBase64 = imageData.toString('base64');
// Make request to upload to Cloudinary
const result = await cloudinary.uploader.upload(
`data:image/png;base64,${imageBase64}`,
{
folder: 'propertypulse',
}
);
imageUrls.push(result.secure_url);
}
propertyData.images = imageUrls;
const newProperty = new Property(propertyData);
await newProperty.save();