Lesen Sie mehr über Cloudinary und seine Preise.
Melden Sie sich bei Cloudinary an und erstellen Sie ein neues Konto, falls Sie noch keins haben.
Sie können das Cloudinary SDK mit npm oder Yarn installieren:
npm install cloudinary
Sie können eine Konfigurationsdatei erstellen, um Ihre Cloudinary-Anmeldeinformationen zu speichern. Es empfiehlt sich, diese in Umgebungsvariablen zu belassen.
Erstellen Sie eine .env.local-Datei in Ihrem Projektstammverzeichnis und fügen Sie Ihre Cloudinary-Anmeldeinformationen hinzu:
CLOUDINARY_URL=cloudinary://: @
// utils/cloudinary.js import { v2 as cloudinary } from 'cloudinary'; cloudinary.config({ cloud_name: process.env.CLOUDINARY_CLOUD_NAME, api_key: process.env.CLOUDINARY_API_KEY, api_secret: process.env.CLOUDINARY_API_SECRET, }); export const uploadImage = async (file) => { try { const result = await cloudinary.uploader.upload(file, { folder: 'your_folder_name', // optional }); return result.secure_url; // Return the URL of the uploaded image } catch (error) { console.error('Cloudinary upload error:', error); throw new Error('Upload failed'); } };
// pages/api/upload.js import { uploadImage } from '../../utils/cloudinary'; export default async function handler(req, res) { if (req.method === 'POST') { const { file } = req.body; // Assume you're sending a file in the body try { const url = await uploadImage(file); res.status(200).json({ url }); } catch (error) { res.status(500).json({ error: error.message }); } } else { res.setHeader('Allow', ['POST']); res.status(405).end(`Method ${req.method} Not Allowed`); } }
// components/ImageUpload.js import { useState } from 'react'; const ImageUpload = () => { const [file, setFile] = useState(null); const [imageUrl, setImageUrl] = useState(''); const handleFileChange = (event) => { setFile(event.target.files[0]); }; const handleSubmit = async (event) => { event.preventDefault(); const formData = new FormData(); formData.append('file', file); const res = await fetch('/api/upload', { method: 'POST', body: formData, }); const data = await res.json(); if (data.url) { setImageUrl(data.url); } else { console.error('Upload failed:', data.error); } }; return (); }; export default ImageUpload;
Führen Sie Ihre Next.js-Anwendung aus und testen Sie die Funktion zum Hochladen von Bildern.
Sie sollten jetzt über eine funktionierende Integration von Cloudinary in Ihrer Next.js-App verfügen! Wenn Sie spezielle Anforderungen haben oder weitere Anpassungen benötigen, fragen Sie einfach nach!
Haftungsausschluss: Alle bereitgestellten Ressourcen stammen teilweise aus dem Internet. Wenn eine Verletzung Ihres Urheberrechts oder anderer Rechte und Interessen vorliegt, erläutern Sie bitte die detaillierten Gründe und legen Sie einen Nachweis des Urheberrechts oder Ihrer Rechte und Interessen vor und senden Sie ihn dann an die E-Mail-Adresse: [email protected] Wir werden die Angelegenheit so schnell wie möglich für Sie erledigen.
Copyright© 2022 湘ICP备2022001581号-3