nextjs使用antd上传文件图片到本地项目
"use client"; import { useAuth } from "@/hooks/useAuth"; import Link from "next/link"; import { Button, message, Upload } from 'antd'; import { UploadOutlined } from '@ant-design/icons'; import type { UploadProps } from 'antd'; export default function Home() { // 验证成功后的 const auth = useAuth(); // const props: UploadProps = { name: 'file', action: `${process.env.NEXT_PUBLIC_HTTP}/api/upload`, headers: { authorization: 'authorization-text', }, onChange(info) { if (info.file.status !== 'uploading') { console.log(info.file, info.fileList); } if (info.file.status === 'done') { message.success(`${info.file.name} file uploaded successfully`); } else if (info.file.status === 'error') { message.error(`${info.file.name} file upload failed.`); } }, }; return <> {auth ? ( <div> <section> <div className="container"> <h1>新闻的编辑上传</h1> <div> <p>上传banner图片</p> <Upload {...props}> <Button icon={<UploadOutlined />}>Click to Upload</Button> </Upload> </div> </div> </section> <section> <div className="container"> <h1>成功案例的上传</h1> </div> </section> </div> ) : ( <Link href="/login">Login</Link> )} </> }
process.env.NEXT_PUBLIC_HTTP是localhost:3000
二
api路由是
// pages/api/upload.js import { writeFile } from "fs/promises"; import { NextResponse } from "next/server"; import path from "path"; export const POST = async (req) => { const formData = await req.formData(); const file = formData.get("file"); if (!file) { return NextResponse.json({ error: "No files received." }, { status: 400 }); } const buffer = Buffer.from(await file.arrayBuffer()); const filename = Date.now() + file.name.replaceAll(" ", "_"); // console.log(formData,file,'dddddddddddddddddddddddddd') try { await writeFile( path.join(process.cwd(), "public/uploads/news/" + filename), buffer ); return NextResponse.json({ Message: "Success", status: 201 }); } catch (error) { console.log("Error occured ", error); return NextResponse.json({ Message: "Failed", status: 500 }); } };