NextJS 13.3 直接使用App简单文件上传和路由

Arn*_*OFC 4 reactjs next.js next.js13

我真的被困住了。有人可以为我提供一个非常简单的使用 NextJS 13.3 文件上传到本地存储的最新版本和功能的代码示例吗?

我需要一个带有提交功能的表单,将 api 请求发送到 APP/API/Routes(例如)并将文件上传到本地服务器存储。

谢谢你!一个完整的简单工作解决方案将非常感激。

我尝试了很多例子,但都已经过时并且不起作用。

小智 6

这是源代码

核心代码

// page.tsx

export default function Home() {
  return (
    <main className="flex min-h-screen flex-col items-center justify-center p-24">
      <form action="/api/file" method="post" encType="multipart/form-data">
        <input type="file" name="file" required />
        <button className="ring-2 px-3 py-2 bg-blue-800 text-white rounded-md">
          upload
        </button>
      </form>
    </main>
  );
}

Run Code Online (Sandbox Code Playgroud)

// route.ts
import { NextRequest, NextResponse } from "next/server";
import { existsSync } from "fs";
import fs from "fs/promises";
import path from "path";

export async function POST(req: NextRequest) {
  const formData = await req.formData();
  console.log(formData);

  const f = formData.get("file");

  if (!f) {
    return NextResponse.json({}, { status: 400 });
  }

  const file = f as File;
  console.log(`File name: ${file.name}`);
  console.log(`Content-Length: ${file.size}`);

  const destinationDirPath = path.join(process.cwd(), "public/upload");
  console.log(destinationDirPath);

  const fileArrayBuffer = await file.arrayBuffer();

  if (!existsSync(destinationDirPath)) {
    fs.mkdir(destinationDirPath, { recursive: true });
  }
  await fs.writeFile(
    path.join(destinationDirPath, file.name),
    Buffer.from(fileArrayBuffer)
  );

  return NextResponse.json({
    fileName: file.name,
    size: file.size,
    lastModified: new Date(file.lastModified),
  });
}

Run Code Online (Sandbox Code Playgroud)