需要使用路由处理程序上传到 Cloudinary 的帮助,我已经查找了如何使用服务器操作来完成此操作,但仍然好奇如何在 API 路由中完成此操作。
我希望这条路线在我的 mongoDB 中创建一个新的 Collection 文档,同时将图像上传到我的 Cloudinary 中。猫鼬查询工作正常,但是当我添加上传功能时,该路由无法再创建 mongoDB 文档,并且没有图像上传到我的 Cloudinary。
// app/api/postman/collection/route.js
import mongoConnection from "@/lib/mongoose/mongoconnection";
import Collection from "@/lib/mongoose/models/Collection";
import { NextResponse } from "next/server";
import { v2 as cloudinary } from "cloudinary";
export async function POST(req, res) {
await mongoConnection();
cloudinary.config({
cloud_name: process.env.CLOUDINARY_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
const { images } = await req.json()
// array of image paths, example: ("/images/the_lich.png")
// located in public folder
console.log(process.env.CLOUDINARY_NAME, process.env.CLOUDINARY_API_KEY, process.env.CLOUDINARY_API_SECRET)
// is getting the correct value
try {
// MULTIPLE UPLOADS, looping through an array of image paths
// for(const image of images) {
// const uploads = await cloudinary.uploader.upload(image, {folder: "my-images"});
// console.log(uploads);
// }
// SINGLE UPLOAD, since my multiple upload didn't work I tried
// doing a single upload, image is located in public folder
// const upload = await cloudinary.uploader.upload("/images/the_lich.png");
// console.log(upload);
const collection = await Collection.create({images})
if (collection) {
return NextResponse.json({message: "Success"}, {status: 200});
} else {
return NextResponse.json({message: "Failed"}, {status: 500});
}
} catch (err) {
return NextResponse.json({message: err.message}, {status: 500});
}
}
我浏览了一些文档,其中提到了有关公共文件夹的一些内容,但我再也找不到它了。
我正在使用 VS Code Postman 扩展来发出相关请求。
我可能会迟到,但这肯定会有帮助https://www.youtube.com/watch?v=P0NE5eUOod4。直接给你答案不会有教育意义 - 一个好的开发人员不能盲目复制粘贴代码!