48 lines
1.5 KiB
JavaScript
48 lines
1.5 KiB
JavaScript
import fs from 'fs';
|
|
import path from 'path';
|
|
import dotenv from 'dotenv';
|
|
dotenv.config({ path: '.env.local' });
|
|
|
|
async function uploadFile(filePath, folderName) {
|
|
const fileBuffer = fs.readFileSync(filePath);
|
|
|
|
const ext = path.extname(filePath).toLowerCase();
|
|
const mimeTypes = {
|
|
'.png': 'image/png',
|
|
'.jpg': 'image/jpeg',
|
|
'.jpeg': 'image/jpeg',
|
|
'.webp': 'image/webp'
|
|
};
|
|
const mimeType = mimeTypes[ext] || 'application/octet-stream';
|
|
|
|
const blob = new Blob([fileBuffer], { type: mimeType });
|
|
|
|
const formData = new FormData();
|
|
formData.append('files', blob, path.basename(filePath));
|
|
formData.append('folder', folderName);
|
|
|
|
console.log(`Uploading ${filePath} to folder ${folderName}...`);
|
|
|
|
try {
|
|
const res = await fetch(`${process.env.OPENINARY_API_URL}/api/upload`, {
|
|
method: 'POST',
|
|
headers: {
|
|
Authorization: `Bearer ${process.env.OPENINARY_API_KEY}`
|
|
},
|
|
body: formData,
|
|
});
|
|
|
|
if (!res.ok) {
|
|
const errorText = await res.text();
|
|
console.error(`Error uploading ${filePath}:`, errorText);
|
|
} else {
|
|
const data = await res.json();
|
|
console.log(`Success: ${data.files[0].url}`);
|
|
}
|
|
} catch (err) {
|
|
console.error(`Exception uploading ${filePath}:`, err.message);
|
|
}
|
|
}
|
|
|
|
uploadFile(path.join(process.cwd(), 'public', 'logo.png'), 'moygrup').then(() => console.log('Done'));
|