NextJS 13.3简单的文件上传使用应用程序直接和路由

fv2wmkja  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(103)

我真的卡住了。有人能提供一个非常简单的最新使用NextJS 13.3文件上传到本地存储的最新版本和功能的代码示例吗?
我需要一个提交函数的形式,发送API请求到应用程序/API/路由(例如),并上传文件到本地服务器存储。
谢谢!一个完整的简单的工作解决方案将是非常感激的。
我尝试了很多例子,但都过时了,不工作。

0yycz8jy

0yycz8jy1#

Here's source code
核心码

// 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>
  );
}

和/或

// 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),
  });
}

相关问题